I read FutureTask class in jsr166, found that outcome object is non-volatile, the comments in code is “non-volatile, protected by state reads/writes” line 75, the state is volatile int. I have read Java Memory Model from Java Language Spec, but not found the accurate answer. Does anybody know the reason?
I read FutureTask class in jsr166, found that outcome object is non-volatile, the comments
Share
consider this program:
If volatile read
vr2seesDONE, it means it happens after volatile writevw1. So we have happens-before relationships:w1 -> vw1 -> vr2 -> r2. Therefore writew1is visible to readr2.However
succeed()isn’t thread safe, sincevr0andvw1are not atomic. If we use CASit fixes the atomicity issue. However, now
w1isn’t necessarily visible tor2. The memory barrier effect of CAS is kind of likeWe have here
vw0 -> vr2 -> r2, butw1is not on the chain, there is now1 -> r2We must do the volatile write
state=DONEafterw1to establish the happens-before chain.or in CAS