When synchronized block execution is completed all the processor cache is flushed or only that object on which synchronized statement acted on will be flushed? In the below example when thread finished execution of method2 does data of obj2 is also flushed to the main memory?
class cls1 {
int x=10;
}
class cls2{
int y=10;
}
class cls3{
cls1 obj1;
cls2 obj2;
public void method2(){
obj2.y=10;
synchronized(obj1){
obj1.x=30;
}
}
public static void main(String[] args) {
final cls3 obj3 = new cls3();
Thread thread1 = new Thread(){
public void run(){
obj3.method2();
}
};
Thread thread2 = new Thread(){
public void run(){
System.out.println(obj3.obj1.x);
}
};
}
}
A happens before relation is established only when the other thread also synchronizes on the lock using which the first thread updated the contents.

In this example Thread B after acquiring the lock on same object M, it will be able to see all the changes that were made before and during the synchronized block. But mind that the lock must be acquired for happens-before relationship to occur.
In your example because System.out.println(obj3.obj1.x); is not printed inside a synchronized block, it does not guarantee happens before.
References:
EDIT: Excellent answer by Peter What is the scope of memory flushed or published to various threads when using volatile and synchronized?
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