ak500
ak500

Reputation: 33

Which thread acquires lock on which object?

I am a newbie to java and I am really confused with the lock acquired by the threads. I really didn't get, whether the caller object gets locked or the called object gets locked??

For example:

public class ThreadA {
    public static void main(String[] args) {
        ThreadB b = new ThreadB();
        b.start();
    }
}

class ThreadB extends Thread {
    int total;
    Demo demo = new Demo();
    public void run() {
        demo.setX();
    }
} 

class Demo {

   private synchronized void setX(){
      System.out.println("hello"); 
   }
}

So, here does the object referred by the reference 'demo' gets locked?

or

the instance of the class 'ThreadB' gets locked??

Upvotes: 2

Views: 80

Answers (1)

MK.
MK.

Reputation: 34527

The instance of class Demo called demo gets locked.
synchronized methods are confusing. I think in most cases it is better to use explicit lock objects, e.g.

private void setX(){
   System.out.println("hello");
   synchronized (this) {
      this.x = 42;
      this.y = 37;
   }
   System.out.println("bye");
}

Upvotes: 1

Related Questions