3

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 ?

j2emanue
  • 60,549
  • 65
  • 286
  • 456
  • 2
    `incrementAndGet` is thread safe http://stackoverflow.com/questions/23597999/is-atomicinteger-incrementandget-thread-safe Why won't you think it'll help? – Tunaki Jul 02 '16 at 19:53
  • i didn't know about this command. its exactly what i was looking for, thanks. – j2emanue Jul 02 '16 at 19:55
  • The `++` operator is not defined on an `AtomicInteger`. You can only use its thread-safe member methods. – Thomas B Preusser Jul 02 '16 at 19:56
  • `synchronized` would work, but reads and writes would both need to be synchronized on the same object, and then `volatile` would be redundant. – Kevin Krumwiede Jul 02 '16 at 19:56

1 Answers1

1

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

Michael
  • 776
  • 4
  • 19