Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache flush on synchronized entry ,exit and volatile read and write

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);
            }
        };
    }
}
like image 383
Pushparaj Avatar asked Nov 16 '25 02:11

Pushparaj


1 Answers

A happens before relation is established only when the other thread also synchronizes on the lock using which the first thread updated the contents.

Happens before

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:

  • http://www.ibm.com/developerworks/library/j-jtp03304/

EDIT: Excellent answer by Peter What is the scope of memory flushed or published to various threads when using volatile and synchronized?

like image 116
Narendra Pathai Avatar answered Nov 17 '25 20:11

Narendra Pathai