Search code examples
javamultithreadingatomic

how to make short hand incrementing atomic in java?


In a multi-threaded environment short hand incrementing like i++ has to do more then one thing and thus another thread can get a intermediate value.

Lets break it down a little, the shorthand incrementation of an integer variable consist of more than one operation. First we have to load the current value of i, increment it and then finally store the new value back. The current thread performing this incrementation may be interrupted in-between any of these three steps, hence this operation is not atomic

Solutions i have thought of: i could use a synchronize block over the i++ and volatile keyword but is there a better way to make the i++ seem atomic to every thread ? I've tried using AtomicInteger i still think it wont help in the case of incrementing short hand with i++, am i right ?


Solution

  • AtomicInteger and its thread-safe methods will work, if you are content with not using i++ Unfortunately, if you want to use i++, it will not be threadsafe