In Concurrency in Practice, it says you can use volatile variables if
Writes to the variable do not depend on its current value.
So, if you have a shared, mutable variable a, and all threads ever do to it is go a++ (they don’t get the value, they just ++).
Then according to the quote, you should be able to make it volatile even though a++ is not atomic, correct?
No, using
++on avolatilevariable is not threadsafe, becauseis equivalent to:
So the write back to
amay happen after another thread has modifiedasince your thread read it, soa++, even ifais volatile, is not threadsafe.You can use
AtomicInteger, which implements threadsafe atomic incrementation.