Inside a synchronized Java static method: happens before the relation for the static variable
Does updating to a static variable inside a method of a synchronized class provide before? Use this as an example:
public class MyClass {
private static boolean isDone = false;
public static synchronized doSomething() {
if (!isDone) {
// ...
}
isDone = true;
}
}
Is the variable isDone
(without volatile
) visible to all threads after updating in this method of a synchronized class? In my opinion, synchronization MyClass.class
by itself does not guarantee that all updates to its static variables are visible to other threads, since there may be a local cache for other threads.
source to share
happens-before is the relationship between two events. One of the events you specified is "update to static variable inside a method of a synchronized class". What other event do you mean? Just reading this variable on another thread? No, normal reading on another thread does not participate in a before-to relationship.
That is, you are correct suggesting synchronization does not guarantee that all variable updates are visible to other threads.
UPDT To ensure that all variable updates are visible to other threads, these threads must also synchronize their reads, that is, do the read inside a method with a synchronized class.
source to share
I found the answer here: https://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#synchronization
After exiting the synchronized block, we exit the monitor, which causes the cache to be lost to main memory, so that the records created by this thread can be seen by other threads. Before we can enter the synchronized block, we have a monitor that has the effect of invalidating the local processor cache, so that the variables will be reloaded from main memory. Then we can see all the entries made visible by the previous version.
source to share
Here's an easier way to think about it that works if you follow good coding practice:
If it is synchronized
, you don't need to worry about it.
This is because if thread A updates any variable and then releases the lock, the update will be visible to thread B after thread B locks the same lock, and if you follow good coding practice your blocks synchronized
will be as large as that possible: you won't touch any shared variables inside a synchronized block that don't need to be synchronized. And, if you follow good coding practice, every variable access (write or read) will be synchronized.
source to share