When you have a method such as the following:
public synchronized void addOne() {
a++;
}
it is equivalent to the following: (correct me if I'm wrong)
public void addOne() {
synchronized(this) {
a++;
}
}
But what is the equivalent to the following method?:
public static synchronized void addOne() {
a++;
// (in this case 'a' must be static)
}
What is a synchronized block that acts the same as a static synchronized method? I understand the static synchronized method is synchronized on the class and not the instance (since there is no instance), but what is the syntax for that?
A synchronized block of code can only be executed by one thread at a time. Synchronization in Java is basically an implementation of monitors . When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method , the monitor belongs to the class.
static methods can be synchronized. But you have one lock per class. when the java class is loaded coresponding java.
It is equivalent to locking on the class object. You can get a reference to the class object by writing the class name followed by .class
. So, something like:
synchronized(YourClass.class) {
}
See the Java Language Specification, Section 8.4.3.6 synchronized
Methods:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With