Hey all, I'm working on some code I inherited, it looks like one thread is setting a boolean member variable while another thread is in a while loop checking it. Will this actually work OK or should I change it to use synchronized getters or setters on the boolean var?
In the case of reading and writing a primitive like bool or int declaring them as volatile will be plenty. When one threads read the other thread would have finished writing. The variable will never be in an invalid state.
It's probably fair to say that on the whole, the volatile keyword in Java is poorly documented, poorly understood, and rarely used. To make matters worse, its formal definition actually changed as of Java 5. Essentially, volatile is used to indicate that a variable's value will be modified by different threads.
Declaring a volatile Java variable means:
- The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
- Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.
We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved.
http://www.javamex.com/tutorials/synchronization_volatile.shtml
Almost certainly you will need to add locking at a higher level. Just adding synchronized
around single accesses to fields rarely helps. Composite operations will not be thread-safe if component operations are independently thread-safe.
As an example consider deleting the contents of a thread-safe document. The document provides two relevant thread-safe operations: deleting contents between two indexes and a length operation. So you get the length and delete from zero to the length, right? Well, there's a race as the document may change length between reading the length and deleting the contents. There is no way to make the operation thread-safe given the operations. (Example taken from Swing Text.)
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