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