Do Atomic variables guarantee a - “happens before relationship”?

夙愿已清 提交于 2021-01-20 12:43:13

问题


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 a volatile variable.
  • set has the memory effects of writing (assigning) a volatile 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!