“Synchonized” in a block vs on a method
Today, in recruting interview, I have been asked the following question: what is the difference between the Java reserved word synchronized
used on a method and this very word in a block? Happily I have known the answer:
Indeed, synchronized
uses an Object to lock on. When a methid is synchronized
, this means the current object is the locker.
Eg: this piece of code:
public synchronized void foo(){ System.out.println("hello world!!!"); }
is equivalent to that:
public void foo(){ synchronized (this) { System.out.println("hello world!!!"); } }
Besides, when synchronized
is used on a static method, the class itself is the locker.
Eg: this piece of code:
public static synchronized void goo() { System.out.println("Chuck Norris"); }
is equivalent to that:
public static void goo() { synchronized (MyClass.class) { System.out.println("Chuck Norris"); } }