Search code examples
javac++concurrencyatomicmemory-barriers

Barriers in java


As in c++ when accessing std::atomics I can partially partially weaken order guarantees using memory_order_acquire or memory_order_release with std::atomics::load() and std::atomics::store(). Or using std::memory_order_relaxed

My question is: is this possible in java? I mean is there any barrier concept in java?


Please correct me if I'm thinking very wrong.


Solution

  • The Java concurrent package should have all the tools you need, including a CyclicBarrier and a Phaser (reusable barrier).

    A correct memory order in Java is guaranteed at any call to a volatile variable, regarding anything that happened before. Since those barriers internally use volatile variables, the memory order is as well guaranteed after each barrier.await() call.

    For a more fine-grain order, you need to use your own volatile variables, but given standard coding (read: not re-inventing the wheel, but using Java library), there is close to never a reason to actually do this.