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?
TL: DR — Yes, Java Concurrency in Practice is still valid and one of the best books to learn Java multithreading and concurrency concepts.
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
If it is accessed only from synchronized blocks is not needed the volatile keyword. Synchronized guarantees that changes to variables accessed inside the synchronized block are visible to all threads entering a synchronized block.
No, using ++
on a volatile
variable is not threadsafe, because
a++
is equivalent to:
int temp = a;
temp = temp + 1;
a = temp;
So the write back to a
may happen after another thread has modified a
since your thread read it, so a++
, even if a
is volatile, is not threadsafe.
You can use AtomicInteger
, which implements threadsafe atomic incrementation.
a++ reads the value of a, since it's equivalent to
So no, you can't safely use a volatile variable in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With