Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 615
j2emanue Avatar asked Apr 10 '26 14:04

j2emanue


1 Answers

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

like image 108
Michael Avatar answered Apr 13 '26 06:04

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!