Java – If you lock an object, do you lock all of its methods?

If you lock an object, do you lock all of its methods?… here is a solution to the problem.

If you lock an object, do you lock all of its methods?

Suppose we have an object foo:

class Foo(){
  public synchronized void instanceMethod(){}
}

var foo = new Foo();

If I lock foo:

synchronized(foo){
  foo.instanceMethod();
}

Am I also locking the instanceMethod() call? Another way to ask – if I lock foo, can another thread call foo.instanceMethod() (simultaneously)?

Solution

if I have a lock on foo, can another thread call foo.instanceMethod()?

They can call it, but the call will wait until the execution leaves your block synchronized on foo, because instanceMethod is synchronized. Declaring an instance method synchronized is roughly equivalent to putting its entire body in a synchronized block on this.

If instanceMethod is not synchronized, then of course the call does not wait.

Note, however, that the synchronized block you are displaying is unnecessary:

synchronized(foo){       // <==== Unnecessary
  foo.instanceMethod();
}

Because instanceMethod is synchronous, it can be:

foo.instanceMethod();

… Unless there’s something else in the block.

Related Problems and Solutions