Recent Posts
Archives

PostHeaderIcon “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:
[java] public synchronized void foo(){
System.out.println("hello world!!!");
}
[/java]
is equivalent to that:
[java] public void foo(){
synchronized (this) {
System.out.println("hello world!!!");
}
}
[/java]
Besides, when synchronized is used on a static method, the class itself is the locker.
Eg: this piece of code:
[java] public static synchronized void goo() {
System.out.println("Chuck Norris");
}
[/java]is equivalent to that:
[java] public static void goo() {
synchronized (MyClass.class) {
System.out.println("Chuck Norris");
}
}
[/java]

Leave a Reply