I know that compound operations such as i++
are not thread safe as they involve multiple operations.
But is checking the reference with itself a t
No, it is not. For a compare the Java VM must put the two values to compare on the stack and run the compare instruction (which one depends on the type of "a").
The Java VM may:
false
In the 1st case, another thread could modify the value for "a" between the two reads.
Which strategy is chosen depends on the Java compiler and the Java Runtime (especially the JIT compiler). It may even change during the runtime of your program.
If you want to make sure how the variable is accessed, you must make it volatile
(a so called "half memory barrier") or add a full memory barrier (synchronized
). You can also use some hgiher level API (e.g. AtomicInteger
as mentioned by Juned Ahasan).
For details about thread safety, read JSR 133 (Java Memory Model).