문제

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