Reputation: 1518
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?
Upvotes: 4
Views: 2871
Reputation: 32458
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.
Upvotes: 11
Reputation: 88
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.
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++;
}
}
Upvotes: 2