Java will synchronized block if changed?

ealeon :
private Object x = new Object();

public void doA() {
   synchronized(x){
       x = new Object();
       //do something
    }
}

public void doB() {
    synchronized(x) {
        //do something 
    }
}

lets say doA() and doB() was called simultaneously but doA() is proceeding first. so B will be blocked until doA() is completed

is this true even if doA() modifies x in the x = new x call? or after this line x = new x in doA() doB() will no longer be blocked because x has changed?

Kröw :

What happens would really depend on how quickly doA() gets run:

If doA() changes the value of x before doB() reaches its synchronized block, then doB() will lock on the new object that doA() created.

If doB() is speedy and the synchronized(x) part gets evaluated before doA() can change the value of x, then doB() will have to wait until doA()'s synchronized block finishes.

Explanation

Whenever Java gets to the synchronized(x) code in either method, it evaluates the variable x, and that variable gives Java an object. So Java then tries to lock on that object, and stay locked on that object. Or, if there's already a lock on that object, it will wait for the lock to go away. (Whenever Java reaches the synchronized(x) code, it takes the value of the variable and ignores forgets the variable itself, so you can change the variable as you please afterwards, but locking and lock checking still happen on the variable's previous value.)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88561&siteId=1