Abhishek kumar Abhishek kumar - 4 months ago 16
Java Question

Method synchronisation among two different object of same class

How does Method synchronisation works among two different objects of the same class .

class abc {
int x = 0;

public synchronized void workOnMember(int y) {
// some code to work on x - data member
}
}

public class dummy123 {
public static void main(String[] args) {
// TODO Auto-generated method stub
abc obj1 = new abc();
abc obj2 = new abc();
obj1.workOnMember(10);
obj2.workOnMember(20);
}
}


Would obj1 wait for obj2 method call ?
or since for each objects separate heap space would be allocated along with members , so obj1.workOnMember() would run independantly of obj2.workOnMember() ?

Thanks

Answer

They would run independently because they are two distinct instances.

Remember that

public synchronized void workOnMember(int y) { 
    // ... 
}

is equivalent to:

public void workOnMember(int y) { 
    synchronized(this) {
        // ... 
    }
}

And in your case, the two this are distinct.