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?
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:See the Java Language Specification, Section 8.4.3.6
synchronizedMethods: