Sam Adamsh
Sam Adamsh

Reputation: 3391

concurrency java

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

Upvotes: 0

Views: 199

Answers (2)

Ender
Ender

Reputation: 1778

The explanation isn't exactly clear but here's what I understand it to be.

Since thread 1 is at line 5 (already through line 3) and hasn't yet hit line 12 (and your saying somewheres in between 3 and 12 thread 1 sets x.b to false), thread 2 should see x.b as whatever thread one just set it to (which is false). Though I don't see that thread 2 actually cares to see x.b in line 3. And it's not clear to me why line 5 (which I don't see) is not synchronized, yet line 12 which sets it to false is synchronized.

Upvotes: 1

ruakh
ruakh

Reputation: 183211

You have somewhat overspecified the terms "first thread" and "second thread"; your question presupposes that the first thread to enter the first synchronized block will also be the first thread to enter the second synchronized block, but there's really no reason to expect that.

However, the first synchronized block doesn't do anything very relevant or interesting — nothing in your code-snippet mutates k, and the first synchronized block merely accesses it — so I'm just going to ignore the fact that it's synchronized. That will simplify the definitions slightly: now "first thread" means the first thread to enter the second synchronized block, and "second thread" means the second thread to enter the second synchronized block. (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.b to true — 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 for k.get("LL") due to things going on elsewhere — then the second thread will see x.b as false, just as one would naïvely expect. This is because

If one action happens-before another, then the first is visible to and ordered before the second.

and

An unlock on a monitor happens-before every subsequent lock on that monitor.

(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.)

Upvotes: 2

Related Questions