user1401646
user1401646

Reputation: 11

locking behavior of synchronous method

A fellow developer is arguing with me that if we call a synchronized method in objectB from another a synchronized method in objectA there is no extra cost to acquire lock on object on objectB because we already have lock on objectA. How do i disprove that?

fellow developers theory - "when you call a synchronized method the thread acquires lock on all objects used in that method."

class ObjectA {

public synchronized void methodA() {
  methodB();
  // do something else
}

}

class ObjectB {

public synchronized void methodB() {
  // do something
}

}

Upvotes: 1

Views: 49

Answers (1)

Vebbie
Vebbie

Reputation: 1695

Tell your fellow developer that:

The thread executing the static synchronized method holds a lock on the class and the thread executing the non-satic synchronized method holds the lock on the object on which the method has been called. (these two locks are different and these threads do not block each other).

For an example:

public class Counter {
    private int count = 0;
    public void increment() {
       synchronized (this) {
       count++;
    }
}
public int getCount() {
    synchronized (this) {
        return count;
    }
}
}

Every Java object created, including every Class loaded, has an associated lock or monitor.

Putting code inside a synchronized block makes the compiler append instructions to acquire the lock on the specified object before executing the code, and release it afterwards (either because the code finishes normally or abnormally).

Between acquiring the lock and releasing it, a thread is said to "own" the lock. At the point of Thread A wanting to acquire the lock, if Thread B already owns the it, then Thread A must wait for Thread B to release it.

In your case, methodB() will be called on object of class ObjectB as it is a non-static method.

So, while entering methodB(), a lock on object(on which the method is being called) of class ObjectB will be owned by the thread as soon as it sees methodB() is synchronized.

Upvotes: 1

Related Questions