Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
DJhon Avatar asked Sep 05 '25 17:09

DJhon


2 Answers

In java, static content are synchronized on the class object where the method defined,

For example

static synchronized void aMethod() {} is equivalent to

static void aMethod() {
      synchronized(YourClass.class){

      }
}

From JLS 8.4.3.6

A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method, the lock associated with the Class object for the method's class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.

OP's question :

why I used synchronization with static and in which "situation"?

The situation is to prevent multiple Threads to execute a static method same time.

like image 118
Abimaran Kugathasan Avatar answered Sep 07 '25 11:09

Abimaran Kugathasan


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++;
    }

}
like image 42
Vinoth K S Avatar answered Sep 07 '25 13:09

Vinoth K S