Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping C++ memory ordering to Java

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)

like image 457
overclockwise Avatar asked Mar 12 '26 16:03

overclockwise


1 Answers

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.

like image 160
MikeMB Avatar answered Mar 14 '26 06:03

MikeMB