If int incrementing/decrementing operations are not atomic in Java 6, that is, they are said to be performed in several steps (read the value, increment, write etc), I would like to see a piece of code that will demonstrate how multiple threads can affect a single int variable in a way that will corrupt it entirely.
For example, elementary steps include, but not cover all, these: i++ ~= put i to the register; increment i (inc asm operation); write i back to memory;
if two or more threads interleave during the process, that would probably mean that the value after two consequent calls to i++ will be incremented only once.
Can you demonstrate a piece of code in java that models this situation in multithreading environment?
Here is the code. Sorry for the
static
, just wanted to save few lines of code, it does not affect the results:This program can print anything between 50000 and 100000, but it never actually printed 100000 on my machine.
Now replace
int
withAtomicInteger
andincrementAndGet()
method. It will always print 100000 without big performance impact (it uses CPU CAS instructions, no Java synchronization).You need to run the test for many iterations as
++
is quick and can run to completion before there is time for there to be a problem.prints
with only 500K I got the following on a basic laptop. On a faster machine you can have a higher iteration count before a problem would be seen.
Running this program on my machine gives