Reputation: 23
I'm learning design patterns and have intermediate experience in Java. I'm attempting to implement the Singleton design pattern and have come across the following code in a method:
public static Singleton getInstance(){
if( firstInstance == null ){
if (firstThread){
firstThread = false;
Thread.currentThread();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Singleton.class.getName()).log(Level.SEVERE, null, ex);
}
}
synchronized(Singleton.class){
if(firstInstance == null){
firstInstance = new Singleton();
}
}
}
return firstInstance;
}
I understand how the method works, but I have a question with one specific part of this code:
synchronized(Singleton.class){
if(firstInstance == null){
firstInstance = new Singleton();
}
}
I know that the synchronized block forces only this part of the code to be synchronized which makes the implementation thread-safe and doesn't slow down the whole method, but why are we wrapping Singleton.class
in parenthesis before the access modifier synchronized
?
My question is more Java-related than it is Design Pattern-related. I tried searching Google and StackOverflow, but I'm not sure what this is actually called which limits my results.
I hope you guys can help me out here.
Thanks in advance!
Upvotes: 2
Views: 212
Reputation: 9093
Because the normal thing to synchronize on in Java is this
(e.g. the current instance). But this method is static
, so there is no instance, just a class. Thus we synchronize on that.
The reason for synchronizing
this part of the method is so two instances aren't created by two threads at once. This could happen if both do the firstInstance == null
check at the same time, and upon both finding it is true
, both decide to create a new instance. This gives us two instances of a Singleton
class, which is obviously very bad.
Also I think you are confused as you call synchronized
an access modifier.
The only access modifiers are private
, public
, and protected
(plus the hidden default one).
Synchronized
is a non-access modifier. A single method can have both access and non-access modifiers such as public static
or private synchronized
.
Note that only synchronized
and static
can have blocks. However, this is more because of what they are used for rather than their modifier classification.
Upvotes: 1
Reputation: 8928
The firstInstance variable is likely a static variable in the Singleton class, containing the only object of that class.
Synchronizing on the class ensures that two different threads don't both try to create the firstInstance object at the same time. That ensures that the firstInstance variable is only initialized once.
Upvotes: 1