I have been going through JCIP and there the author says..
A special case of thread confinement applies to volatile variables. It is safe to perform read-modify-write operations on shared volatile variables as long as you ensure that the volatile variable is only written from a single thread
For instance count++ is considered a compound operation (reading the value,adding one to it,and updating the value) and declaring count as volatile does not make this operation atomic, so thread safety is not guaranteed here !! Am i right ?? But here the author says we can fix it if we ensure that the volatile variable is only written from a single thread. I am failing to understand this. Please provide an illustration.
A typical use case could look something like this:
public class Foo implements Runnable {
private volatile int itemsProcessed;
public int getItemsProcessed() { return itemsProcessed; }
@Override
public void run() {
while (true) { //this is just an example so we don't care about stopping
processItem(); //process a single item
itemsProcessed++;
}
}
}
Now others can query your thread's progress without extra synchronization but only the thread itself is allowed to update it. For everyone else the field is read-only.
Without volatile
other threads may not see any change to itemProcessed
at all, or may even see them in a wacky order, sometimes increasing, sometimes decreasing.
The only time multiple threads are okay to write to a volatile
variable without any extra synchronization is if the writes are idempotent (that is, multiple writes have the same effect as a single one). This can be seen in this pattern used to stop a thread:
public class Foo implements Runnable {
private volatile boolean stopped = false;
public void stopProcessing() {
stopped = true;
}
public int getItemsProcessed() { return itemsProcessed; }
@Override
public void run() {
while (!stopped) {
processItem(); //process a single item
}
}
}
Here the only thing other threads can do is set stopped
to true. It doesn't matter how many of them do it and in what order, the result will always be the same.