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.
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.
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())
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
No, you should be using something like java.util.concurrent.atomic.AtomicInteger
. Look at its getAndIncrement()
method.
++ 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.