In the following code:
class A { private int number; public void a() { number = 5; } public void b() { while(number == 0) {
If method b is called and then a new thread is launched that starts method a, then method b does not guarantee to ever see the change in number and therefore b never exit.
Of course, we could do number volatile to solve this problem. However, for academic reasons, suppose volatile not an option:
JSR-133 Frequently Asked Questions :
After exiting the synchronized block, we exit the monitor, which flushes the cache to the main memory , so that the entries made by this thread can be visible to other threads. Before we can enter a synchronized block, we will get a monitor that has the effect of invalidating the local processor cache so that the variables are reloaded from the main memory.
It seems like I just need both a and b to enter and exit any synchronized -Block in general, no matter which monitor they use. More precisely, it sounds like this:
class A { private int number; public void a() { number = 5; synchronized(new Object()) {} } public void b() { while(number == 0) {
... will fix the problem and ensure that b sees the change to a and therefore also ends.
However, the frequently asked questions also clearly state:
Another consequence is the following pattern, which some people use to force the memory barrier, does not work:
synchronized (new Object()) {}
This is actually non-op, and your compiler can completely remove it, because the compiler knows that no other thread will synchronize the same monitor. You must establish a connection between events and one thread in order to see the results of another.
Now this is confusing. I thought that a synchronized statement would cause a cache reset. Of course, it cannot clear the cache from main memory so that changes in main memory can only be displayed by threads that are synchronized on one monitor, especially since for volatile, which basically does the same, we don’t even need a monitor, or I am wrong there? So why is it non-op and does not cause b termination of the warranty?