Is the pre-increment operator thread-safe?

Tragic Pixel picture Tragic Pixel · Oct 3, 2011 · Viewed 9.6k times · Source

I'm making a program in java that races a few cars against each other. Each car is a separate thread.

When cars complete the race, each one all calls this method. I've tested the method at varying timer speeds, and it seems to work fine. But I do realize that each thread is accessing the variable carsComplete, sometimes at the exact same time (at least at the scope the date command is giving me).

So my question is: is this method thread-safe?

 public static String completeRace()
 {
      Date accessDate = new Date();
      System.out.println("Cars Complete: " + carsComplete + " Accessed at " + accessDate.toString());
      switch(++carsComplete)
      {
           case 1: return "1st";
           case 2: return "2nd";
           case 3: return "3rd";
           default: return carsComplete + "th";    
      }
 }

Answer

duffymo picture duffymo · Oct 3, 2011

No, you should be using something like java.util.concurrent.atomic.AtomicInteger. Look at its getAndIncrement() method.