简体   繁体   中英

Does synchronization allow visibility to all variables after synchronized method call?

public class Test {
int a = 0;
int b = 0;

public synchronized void setAB(int a, int b) {
    this.a = a;
    this.b = b;
}

public synchronized int getA() {
    return a;
}

public int getB() {
    return b;
}

Thread-1 calls setAB(1,5) - sets value of a and b atomically.

Thread-2 calls getA() - synchronized access. this calls establishes happens before relationship with above one. thread should be able to see updated value for a.

Thread-2 calls getB() - this is non-synchronized call. will it see updated for b ie 5?

In general for the getB() call there is no "happens before relationship", no visibility guarantee. It is important to synchronize both reads and writes, and to synchronize them on the same lock .

However, if getB() is called after getA() in the same thread, then the "happens before relationship" has already been established, and the thread is guaranteed to see all changes.

It is explained here (with my added emphasis):

An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM