Matt and I were talking this week about whether ++ is an atomic operation in Java.. He’s written it up in his Blog so I thought I would add my 2c here. I hadn’t really thought about it before and my initial reaction was to think it would be implemented with an iinc bytecode instruction. As Matt points out that’s only true for local variables for which atomicity isn’t a big deal.
Nevertheless, I had to take exception with a statement in Bruce Eckel’s original article:
“… and if you’re coming from C++ or some other low-level background, you would expect the increment to be an atomic operation, because increment is usually implemented as a microprocessor instruction”
C/C++ don’t really address thread interactions and the above statement is certainly not true on a RISC processor. It is just as prone as the Java code to thread interactions. I guess Bruce was thinking in CISC. It certainly is a single instruction on a x86 CISC processor but even there that could fail on a multiprocessor system.
So, lock up your variables …