-1

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?

randomcompiler
  • 309
  • 2
  • 14

1 Answers1

2

No.

All access to hasDataToProcess is within blocks synchronized on the same lock. volatile is not required.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • How does using synchronized solves the issue? As I understand volatile ensures that all reads and writes happen into main memory. So in above case (where volatile is not used) it is possible that if thread A sets it to "true" it only happens in local cache for thread A. Now when thread B reads it, it reads it from the main memory, resulting in reading "false" which is unexpected. Could you please explain a bit more on these lines. Synchronized only ensures that only one thread enters into synchronized methods at a time. Right? – randomcompiler Jan 04 '15 at 14:41
  • 1
    @abhishek08aug - Wrong. `synchronized` causes the thread to appropriately refresh its cache on entry to the block. – Hot Licks Jan 04 '15 at 14:48
  • Thanks! Hot Licks! That was the root cause of doubt! – randomcompiler Jan 04 '15 at 17:36
  • @abhishek08aug This is a common myth. The `volatile` keyword has nothing to with whether reads or writes happen into main memory. Modern hardware just doesn't work that way. The `volatile` keyword ensures that reads and writes are visible to other threads immediately. This has nothing to do with main memory at all and, on modern CPUs, is done entirely in caches. – David Schwartz Mar 15 '16 at 22:41