Is the pre-increment operator thread-safe?

前端 未结 5 611
孤城傲影
孤城傲影 2020-12-03 17:42

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.

相关标签:
5条回答
  • 2020-12-03 17:49

    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 讨论(0)
  • 2020-12-03 17:55

    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())
    
    0 讨论(0)
  • 2020-12-03 18:05

    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

    0 讨论(0)
  • 2020-12-03 18:07

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

    0 讨论(0)
  • 2020-12-03 18:09

    ++ 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.

    0 讨论(0)
提交回复
热议问题