Search
Calendar
May 2017
S M T W T F S
« Sep    
 123456
78910111213
14151617181920
21222324252627
28293031  
Your widget title
Archives

Posts Tagged ‘synchronized’

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:

    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");
        }
    }