[concurrency-interest] Synchronization blocks, locks and reorderings

Unmesh joshi unmesh_joshi at hotmail.com
Tue Jan 22 23:01:08 EST 2008

I was reading http://today.java.net/pub/a/today/2004/04/13/JSR133.html. Discussing reordering there, 
class Reordering {  int x = 0, y = 0;  Object l = new Object();  public void writer() {    x = 1;    synchronized (l) {      y = 2;    }  }  public void reader() {    synchronized (l) {      int r1 = y;      int r2 = x;    }  }}
In the happens-before discussion it is stated that, 
"A thread calling reader() will now see the values of x and y placed there by the thread calling writer(). The writer() method contains four actions -- write to x, lock l, write to y, and unlock l. By the program order rule, the writes to x and y happen before the unlock of l. Similarly, the reader() method contains four actions -- lock l, read x, read y, and unlock l, and again by the program order rule the reads of x and y happen after the lock operation. Since by the monitor rule, the unlock operation in writer() happens before the lock operation in reader(), we can see (by transitivity) that the writes to x and y in writer() happen before the reads of x and y in reader(), and therefore the correct values are visible to the thread calling reader()."
I am little confused here, 
1. Because variable x is never read in synchronized block of writer, it isn't compiler free to reorder read to x after write to y? Or there are no reordering allowed around synchronization blocks?
2. In the discussion, its stated that "the unlock operation in writer() happens before the lock operation in reader()". How can this be guaranteed? It can very well be exactly opposite, right?
Post ads for free - to sell, rent or even buy.www.yello.in
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20080123/b0c168e0/attachment.html 

More information about the Concurrency-interest mailing list