If I have a synchronised method in a class then the synchronization is applied only on the class or also on the objects which the method is modifing.
For example if I have a class A as below
public class A {
private int x;
public void setX(int x) {
this.x = x;
}
}
And there are two classes B and C which are having some method to set the value of x. Like
public class B implements Runnable {
private A a;
public B(A a) {
this.a = a;
}
public synchronized void setX(A a) {
int tempX = 0;
.... //Some logic to calculate tempX value
a.setX(tempX);
}
@Override
public void run() {
this.setX(a);
}
}
Class C will also have a synchronised method to set value of x.
Now if I create an object of A and pass the same object to B and C, will the synchronization happen on object a also or we need to synchronize setX of class A.
Note: Since I am learning threads, so please bear with me if the question sound stupid. I am just trying to understand what all happens if a synchronized method is called.