Skip to content
Advertisement

Synchronization with static block

I have a question: can we use the static keyword with a synchronized method? As we all know that static is related to class and synchronization is used to block an object, using synchronized with static doesn’t make any sense to me. So why and in which situation would I use synchronization with the static keyword?

Advertisement

Answer

I think this will help you:

For those who are not familiar static synchronized methods are locked on the class object e.g. for string class its String.class while instance synchronized method locks on current instance of Object denoted by this.

Since both of these object are different they have different locks, so while one thread is executing the static synchronized method, the other thread doesn’t need to wait for that thread to return. Instead it will acquire a separate lock denoted by the .class literal and enter into static synchronized method.

This is even a popular multi-threading interview questions where interviewer asked on which lock a particular method gets locked, some time also appear in Java test papers.

An example:

public class SynchornizationMistakes {
    private static int count = 0;

    //locking on this object lock
    public synchronized int getCount(){
        return count;
    }

    //locking on .class object lock
    public static synchronized void increment(){
        count++;
    }

}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement