问题
I have a question in singleton pattern. In singleton pattern we write
synchronized(ClassName.class){
// other code goes here
}
What is the purpose of writing ClassName.class
?
回答1:
In a member method (non-static) you have two choices of which monitor (lock) to use: "this" and "my class's single static lock".
If your purpose is to coordinate a lock on the object instance, use "this":
...
synchronized (this) {
// do critical code
}
or
public synchronized void doSomething() {
...
}
However, if you are trying to have safe operations including either:
static methods
static members of your class
Then it is critical to grab a class-wide-lock. There are 2 ways to synchronize on the static lock:
...
synchornized(ClassName.class) {
// do class wide critical code
}
or
public static synchronized void doSomeStaticThing() {
...
}
VERY IMPORTANTLY, the following 2 methods DO NOT coordinate on the same lock:
public synchronized void doMemberSomething() {
...
}
and
public static synchronized void doStaticSomething() {
...
}
回答2:
Each class (for example Foo
) has a corresponding, unique instance of java.lang.Class<Foo>
. Foo.class
is a literal of type Class<Foo>
that allows getting a reference to this unique instance. And using
synchronized(Foo.class)
allows synchronizing on this object.
回答3:
The object that you pass into the synchronized block is known as a monitor. Since the object that represents the class className.class
is guaranteed to only exist once in the JVM it means that only one thread can enter that synchronized block.
It is used within the singleton pattern to ensure that a single instance exists in the JVM.
来源:https://stackoverflow.com/questions/26946728/why-do-we-write-synchronizedclassname-class