2

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.

deeiip
  • 3,319
  • 2
  • 22
  • 33
  • The JLS section on the Java memory model describes the behavior of Java memory "barriers": http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4 – Drew MacInnis Nov 20 '13 at 23:38

3 Answers3

2

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.

TwoThe
  • 13,879
  • 6
  • 30
  • 54
0

Yes, Java concurrency does allow a sort of latch or barrier. Look at CountDownLatch and CyclicBarrier.

These both are created with a fixed number of threads in mind, passed as a constructor parameter. When enough threads await() this barrier then it will release for all threads.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

Not sure if I have this right but a quick scan of C++11 memory_order_acquire and memory_order_release semantics? suggests that you may be looking for:

volatile variable;

Please see Volatile Vs Static in java for a little more on volatile etc.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • I's asking about relaxing order is possible or not in java – deeiip Nov 21 '13 at 00:16
  • See [Instructions reordering in Java JVM](http://stackoverflow.com/q/12554570/823393) - it is relaxed by default if the JVM wants to. It is **not** a simple issue. – OldCurmudgeon Nov 21 '13 at 00:38