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
?
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
?
Each class (for example
Foo
) has a corresponding, unique instance ofjava.lang.Class<Foo>
.Foo.class
is a literal of typeClass<Foo>
that allows getting a reference to this unique instance. And usingallows synchronizing on this object.
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.
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":
or
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:
or
VERY IMPORTANTLY, the following 2 methods DO NOT coordinate on the same lock:
and