I'm translating a small C++ snippet to java, and I'm not 100% confident around memory orderings/fences. Is this correct:
C++:
std::atomic<size_t> seq;
...
seq.store(1,std::memory_order_release);
...
seq.load(std::memory_order_acquire);
How I think it should translate to Java:
unsafe.putLong(addr,1);
unsafe.storeFence();
unsafe.getLong(addr);
unsafe.loadFence();
Is this along the right lines? (and yes there is a reason for using unsafe vs just using an AtomicLong)
The correct ordering ist as follows:
unsafe.storeFence(); // this fence has to come before the store!
unsafe.putLong(addr,1);
unsafe.getLong(addr);
unsafe.loadFence();
The purpose of the c++ code is usually to ensure, that all stores, which have happened before seq.store(1,std::memory_order_release) in one thread are visible to all loads after seq.load(std::memory_order_acquire); in another thread, as soon as the store of 1 to seq itself becomes visible.
In order to transfer this to Java, you have to ensure, that no loads are reordered before unsafe.getLong(addr); and no stores are reordered after unsafe.putLong(addr,1);
If you put the storeFence behind the store, you don't get any guarantees about how that store is reordered compared to any other store.
If your c++ code has a different purpose, the answer might vary but for that you'd have to show an example code that demonstrates what you are trying to achieve.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With