static ConcurrentHashMap k;
X x;
//line 3:
synchronized(k){ x = k.get("LL");}
// line 5
// line 12:
synchronized(k){if(x.b){x.b = false;}}
‘k’ is a shared map. First thread goes through line 3, second thread goes through line 3 when thread 1 is at line 5, thread one alters x.b to false, what x.b does thread 2 see? Line 5 is meant to show that thread 2 gets its x before thread one got in the second synch block
You have somewhat overspecified the terms “first thread” and “second thread”; your question presupposes that the first thread to enter the first
synchronizedblock will also be the first thread to enter the secondsynchronizedblock, but there’s really no reason to expect that.However, the first
synchronizedblock doesn’t do anything very relevant or interesting — nothing in your code-snippet mutatesk, and the firstsynchronizedblock merely accesses it — so I’m just going to ignore the fact that it’ssynchronized. That will simplify the definitions slightly: now “first thread” means the first thread to enter the secondsynchronizedblock, and “second thread” means the second thread to enter the secondsynchronizedblock. (O.K. so far?) That matter of definition out of the way . . .Assuming that there’s no possibility of some other thread coming in and setting
x.btotrue— or, for that matter, of the first thread doing so, in code that’s after the snippet that you quote — and similarly, no possibility of the two threads getting completely different results fork.get("LL")due to things going on elsewhere — then the second thread will seex.basfalse, just as one would naïvely expect. This is becauseand
(Both of the above quotations are from §17.5.5 of The Java Language Specification, Java SE 7 Edition; see that section, and the section before it, for more formalities.)