This question already has an answer here:
I was looking into the singleton design pattern when it comes to the point to provide thread safe to it so here we use this block of code to check if the instance is already created or not.
if (instance == null) {
instance = new DraconianSingleton();
}
and then here we kept this inside the synchronized block to provide thread safe to it like this:
synchronized (DclSingleton .class) {
if (instance == null) {
instance = new DclSingleton();
}
}
but here comes the definition and drawback and why to use drawback: Despite this class being thread-safe, we can see that there’s a clear performance drawback: each time we want to get the instance of our singleton, we need to acquire a potentially unnecessary lock.
To fix that, we could instead start by verifying if we need to create the object in the first place and only in that case we would acquire the lock.
So here we use the double check
public static DclSingleton getInstance() {
if (instance == null) {
synchronized (DclSingleton .class) {
if (instance == null) {
instance = new DclSingleton();
}
}
}
return instance;
}
My question is the "The First if block will check for the instance and then it will go inside the synchronized block if instance returns null(not created any object before) then why we need another same condition there.
What if we remove the second if block it works properly against the different threads right? "
Here is the complete class
public class DclSingleton {
private static volatile DclSingleton instance;
public static DclSingleton getInstance() {
if (instance == null) {
synchronized (DclSingleton .class) {
if (instance == null) {
instance = new DclSingleton();
}
}
}
return instance;
}
// private constructor and other methods...
}
Aucun commentaire:
Enregistrer un commentaire