Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you have a lock on an object, do you have a lock on all its methods?

Say we have a object foo:

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

var foo = new Foo();

if I have a lock on foo:

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

do I also have a lock on the instanceMethod() call? Another way of asking the question - if I have a lock on foo, can another thread call foo.instanceMethod() (simultaneously)?


1 Answers

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

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

If instanceMethod weren't synchronized, then of course the call wouldn't wait.

Note, though, that the synchronized block you've shown is unnecessary:

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

Because instanceMethod is synchronized, that can just be:

foo.instanceMethod();

...unless there's something else in the block as well.

like image 197
T.J. Crowder Avatar answered Dec 09 '25 06:12

T.J. Crowder