« Archives in December, 2013

Java Concurrency, Volatile and Synchronized Blocks

Why Synchronized Blocks are not Enough

So I was reading “Effective Java” by Josh Bloch and got to the chapter on Concurrency (chapter 10).  I thought I had a basic understanding of synchronization blocks and volatile, but I was a little wrong.

  • Volatile – Ensures reading a variable is the most up-to-date at the time of the read
  • synchronized – Ensures a “lock” is put on whatever is being modified within your block.  Mutual exclusion of threads accessing anything being modified within the block.  Avoids other threads seeing things in an invalid state.

Now my definitions are not 100% clear, but they work for me and any comments would be appreciated.

It might be a good time to read this guy’s article.

Based on the above definitions…

Synchronizing modification of a variable does not guarantee that those changes are communicated to another thread, but why?

It is because of optimizations by the JVM.  In “Effective Java” this example is given:

// Cooperative thread termination with a volatile field
public class StopThread {
  private static boolean stopRequested;
  public static void main(String[] args) throws InterruptedException {
    Thread backgroundThread = new Thread(new Runnable(){
      public void run() {
      int i = 0;
      while (!stopRequested)
        i++;
      }
    });
    backgroundThread.start();
    TimeUnit.SECONDS.sleep(1);
    stopRequested = true;
  }
}

Without using the keyword volatile for the stopRequested variable you let the JVM optimize the while loop to potentially something like this:

int i = 0;
if(!stopRequested){
  while(true){
    i++;
  }
}

This would result in the thread never terminating.

Conclusions

The volatile not only ensures that the different threads update their memory between one another, but also protects you from unseen optimizations.

Now I would like to test this myself, because it seems puzzling to me that this optimization would occur on a non-final variable, but according to Josh Bloch
this is what the HotSpot JVM will do. It is called hoisting optimization.