问题
I have a requirement where I need to publish results of 'n' threads upon their completion. For checking if all the threads completed, I am using an AtomicInteger (incrementAndGet()) and comparing its value against a final variable. Before doing the check, I'm writing the results of individual threads to a shared object (into a concurrent-hashmap, as non-synchronized data structures dint seem to be adequate). So, my question is will all the threads complete writing to the shared object (and will the main thread be able to see a consistent memory), before my counter passes the 'if' condition ?
Here's sample code :
public void run() {
//Values is a concurrent hashMap.
values.put(Thread.currentThread().getName(), Thread.currentThread().getName());
if(counter.incrementAndGet() == 5) {
//Do something
}
}
回答1:
See the package summary for java.util.concurrent.atomic
:
The memory effects for accesses and updates of atomics generally follow the rules for volatiles, as stated in The Java Language Specification (17.4 Memory Model):
get
has the memory effects of reading avolatile
variable.set
has the memory effects of writing (assigning) avolatile
variable.- [..]
compareAndSet
and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.
incrementAndGet()
comprises both set and get operations, which means you do have a full happens-before edge.
来源:https://stackoverflow.com/questions/44191549/do-atomic-variables-guarantee-a-happens-before-relationship