1

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.

nascent
  • 117
  • 4
  • I dont see it as a duplicate of http://stackoverflow.com/questions/7533048/object-synchronization. My question is what all gets locked when i call a synchronized method. Question in linked provided is about the object type which can be synchronized. – nascent Dec 25 '13 at 10:49

3 Answers3

3

The code that you've shown synchronises on an instance of B. Presumably, your other method will synchronise on an instance of C. Therefore, you're looking at two separate locks - the methods won't lock each other out at all, and you haven't really synchronised anything.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
1

As you are passing in a A class to your setX method, it will be this which is set, not your private A class.

Also, there is no relationship whatever between B.setX and C.setX so there will be two completely different synchronizations.

In reality, setting synchronization on A.setX would be more meaningful.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Each synchronized method or block specifies or implies some object. For a static method it is the class object for its class. For a non-static method it is the target object, its this.

Synchronization operates among methods and blocks that synchronize on the same object. Synchronization has no impact on non-synchronized code, or on code that is synchronized on a different object.

Your synchronized method would only synchronize with code that is synchronized on the same B instance.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75