开发者

Is the pre-increment operator thread-safe?

I'm making a program in java that races a few c开发者_如何学Pythonars 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";    
      }
 }


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


Pre-increment on int is not thread safe, use AtomicInteger which is lock-free:

AtomicInteger carsComplete = new AtomicInteger();

//...

switch(carsComplete.incrementAndGet())

BTW the code below is not thread safe as well. Can you tell why?

carsComplete.incrementAndGet();
switch(carsComplete.get())


++ operator is not atomic. Look at here http://madbean.com/2003/mb2003-44/. For atomic operations you can use AtomicInteger

AtomicInteger atomicInteger = new java.util.concurrent.atomic.AtomicInteger(0)

and every time you want to increment you can call atomicInteger.incrementAndGet() method which returns a primitive int. 0 is the default initial value for the atomic integer.


Same as in C++ the operator ++ is not atomic.

It is actually more than 1 instruction being executed under the hood (don't be fooled by seeing just a simple ++i; it is load/add/store) and since there is more than 1 instruction involved without synchronization you may have various interleavings with wrong results.

If you need to incrent the carsComplete in a thread-safe manner you can use java's construct AtomicInteger or you could synchronize the whole method


Question is “is pre increment operator thread safe ?”

Ans : No , Why ? because of number of instructions involved. Atomic means single operation , here load/add/store operations need to be performed. So not an atomic operation.

  Same for post increment.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜