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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With