Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 396
bohanl Avatar asked Aug 22 '26 19:08

bohanl


1 Answers

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.

like image 161
Alexei Kaigorodov Avatar answered Aug 24 '26 11:08

Alexei Kaigorodov