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

user5047085 :

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)?

T.J. Crowder :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99462&siteId=1