VarHandle get/setOpaque

后端 未结 2 1649
时光说笑
时光说笑 2021-01-05 03:22

I keep fighting to understand what VarHandle::setOpaque and VarHandle::getOpaque are really doing. It has not been easy so far - there are

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-05 03:36

    The opaque means that the thread executing opaque operation is guaranteed to observe its own actions in program order, but that's it.

    Other threads are free to observe the threads actions in any order. On x86 it is a common case since it has

    write ordered with store-buffer forwarding

    memory model so even if the thread does store before load. The store can be cached in the store buffer and some thread being executed on any other core observes the thread action in reverse order load-store instead of store-load. So opaque operation is done on x86 for free (on x86 we actually also have acquire for free, see this extremely exhaustive answer for details on some other architectures and their memory models: https://stackoverflow.com/a/55741922/8990329)

    Why is it useful? Well, I could speculate that if some thread observed a value stored with opaque memory semantic then subsequent read will observe "at least this or later" value (plain memory access does not provide such guarantees, does it?).

    Also since Java 9 VarHandles are somewhat related to acquire/release/consume semantic in C I think it is worth noting that opaque access is similar to memory_order_relaxed which is defined in the Standard as follows:

    For memory_order_relaxed, no operation orders memory.

    with some examples provided.

提交回复
热议问题