I came across this example on http://tutorials.jenkov.com/java-concurrency/thread-signaling.html:
public class MySignal{
protected boolean hasDataToProcess = false;
public synchronized boolean hasDataToProcess(){
return this.hasDataToProcess;
}
public synchronized void setHasDataToProcess(boolean hasData){
this.hasDataToProcess = hasData;
}
}
What I do not understand is why the volatile keyword not used while declaring boolean "hasDataToProcess". As in case thread A sets it to true, it might only get reflected in its local cache and not in main memory and so thread B may never see it set to true if that is reading from main memory or from its separate local cache?
In an earlier chapter in this tutorial writer explains that how important it is to declare a variable volatile but then he presents an example which does not go along with the earlier guideline and so I am a bit confused about the usage of volatile.
Please help in understanding when to use or not use volatile and whether it is required in this piece of code or not? If yes, why? if not, why not?