Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - is there any reason to check if a singleton is null twice?

I have come across some code, where the developer is constantly checking if the singleton is null twice with a nested if - like in the code below:

private static processManager singleton = null;

...

public synchronized static processManager getInsatnce() throws Exception {

    if(singleton == null) {
      if(singleton == null){
             singleton = new processManager();
       }
     }
     return singleton
}

I cannot see any reason why this might be, but there are numerous instances in the code, so thought there might be a reason?

like image 950
Pectus Excavatum Avatar asked Mar 19 '13 11:03

Pectus Excavatum


People also ask

Why do we need double check Singleton?

Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle.

Why should you avoid singletons?

By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.

What is one of the most common mistakes you can make when implementing a singleton?

A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class.

How do you avoid cloning in Singleton?

Prevent Singleton Pattern From Cloning To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception, as shown in the below code.


1 Answers

Your code doesn't demonstrate the case properly. This stems from the double-checked idiom, where it does make sense:

// Double-check idiom for lazy initialization of instance fields.
private volatile FieldType field;
FieldType getField() {
    FieldType result = field;
    if (result == null) { // First check (no locking)
        synchronized(this) {
            result = field;
            if (result == null) // Second check (with locking)
                field = result = computeFieldValue();
        }
    }
    return result;
}

Read about it over here.

Be careful to note that this idiom is a good choice only for instance fields. In your question you have a static field, for which case a much simpler idiom is the primary choice: the lazy initialion holder class idiom:

// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
    static final FieldType field = computeFieldValue();
}
static FieldType getField() { return FieldHolder.field; }
like image 183
Marko Topolnik Avatar answered Sep 27 '22 15:09

Marko Topolnik