Can static methods be synchronized?

static methods can be synchronized. There is only one copy of the static data
you're trying to protect, so you only need one lock per class to synchronize static
methods—a lock for the whole class. There is such a lock; every class loaded in Java
has a corresponding instance of java.lang.Class representing that class. It's that
java.lang.Class instance whose lock is used to protect the static methods of
the class (if they're synchronized).
There's nothing special you have to do to
synchronize a static method:
public static synchronized int getCount() {
return count;
}

this could be replaced with code that uses a synchronized block. If the
method is defined in a class called MyClass, the equivalent code is as follows:
public static int getCount() {
synchronized(MyClass.class) {
return count;
}}
What's that MyClass.class thing? That's called a class literal. It's a
special feature in the Java language that tells the compiler (who tells the JVM): go
and find me the instance of Class that represents the class called MyClass.
You can also do this with the following code:
public static void classMethod() {
Class cl = Class.forName("MyClass");
synchronized (cl) {
// do stuff
}}

No comments:

Post a Comment