Search code examples
javamultithreadingthread-synchronization

Synchronization on instance variable


In the below example, lock is obtained on instance variable employee (not on this), but still Threads of TestClass1 are getting locked while entering synchronized block. Any advice why is this behaviour. As far as my understanding it should get locked if its synchronization is on this.

public class TestClass{
  public static void main(String args[]){
    TestClass1 obj = new TestClass1();
    Thread t1 = new Thread(obj, "T1");
    Thread t2 = new Thread(obj, "T2");
    t1.start();
    t2.start();
  }
}

class TestClass1 implements Runnable{

Employee employee = new Employee();

public void myMethod () {
    synchronized (employee) {
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void myOtherMethod() {
    synchronized (employee) {
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void run() {
    myMethod();
    myOtherMethod();
}
}

Solution

  • You are using the same TestClass1 instance for both threads, therefore they are using the same Employee instance to lock on.

    To get them to use different locks, you need to do:

    Thread t1 = new Thread(new TestClass1(), "T1");
    Thread t2 = new Thread(new TestClass1(), "T2");