简体   繁体   中英

Inside Java synchronized static method: happens before relationship for static variable

Does an update to static variable inside synchronized class method guarantee to have happens before? Use this as an example:

public class MyClass {
    private static boolean isDone = false;

    public static synchronized doSomething() {
        if (!isDone) {
            // ...
        }

        isDone = true;
    } 
}

Is variable isDone (without being volatile ) visible to all threads after getting updated inside this synchronized class method? In my understanding, synchronization on MyClass.class itself makes no guarantee that all updates to its static variables are visible to other threads since other threads might have a local cache for it.

happens-before is a relationship between two events. One of the event you pointed out: "update to static variable inside synchronized class method". What other event do you have in mind? Plain reading that variable in another thread? No, plain reading in another thread does not participate in happens-before relationship.

That is, you are right suggesting synchronization makes no guarantee that all updates to variables are visible to other threads.

UPDT To guarantee that all updates to variables are visible to other threads, that threads also have to synchronize their reads, that is, make reading inside a synchronized class method.

I found the answer here: https://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#synchronization

After we exit a synchronized block, we release the monitor, which has the effect of flushing the cache to main memory, so that writes made by this thread can be visible to other threads. Before we can enter a synchronized block, we acquire the monitor, which has the effect of invalidating the local processor cache so that variables will be reloaded from main memory. We will then be able to see all of the writes made visible by the previous release.

Here is a simpler way of thinking about it that works if you follow good coding practice:

If it's synchronized you don't have to worry about it.

That's because, If thread A updates any variable and then releases a lock, the update will be visible to thread B after thread B locks the same lock, and if you follow good coding practice, then your synchronized blocks will be as small as possible: You won't be touching any shared variables inside the synchronized block that don't need synchronization. And, if you follow good coding practice, then every access to the variable (write or read ) will be synchronized.

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