简体   繁体   中英

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 xb to false, what xb 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 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. (OK so far?) That matter of definition out of the way . . .

Assuming that there's no possibility of some other thread coming in and setting xb 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 xb 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.)

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 xb to false), thread 2 should see xb as whatever thread one just set it to (which is false). Though I don't see that thread 2 actually cares to see xb 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM