سؤال

When using a CyclicBarrier for synchronizing threads in Java, do they synchronize non-volatile variables?

int a = 0;
int b = 0;
CyclicBarrier barrier = new CyclicBarrier(2);

/*** Thread 1 ***/
public void run() {
    a = 2;
    barrier.await();

    doSomeStuff(b); // no side-effects
}

/*** Thread 2 ***/
public void run() {
    b = 3;
    barrier.await();

    doSomeStuff(a); // no side-effects
}

Can we be sure that on Thread 1's doSomeStuff call b has been set to 3? When trying it's always 3...

هل كانت مفيدة؟

المحلول

Yes, visibility happens as you would expect, as you can see from the javadoc for the CyclicBarrier class:

Memory consistency effects: Actions in a thread prior to calling await() happen-before actions that are part of the barrier action, which in turn happen-before actions following a successful return from the corresponding await() in other threads.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top