Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Lazy Initializing Singleton

The pattern to create singletons seems to be something like:

public class Singleton {
    private static final Singleton instance = new Singleton();
    private Singleton(){
    }

    public static Singleton getInstance()
    {
        return instance;
    }
}

However my problem is how do you Unit with a class like this if the Singleton Constructor does something that is not unit test friendly e.g. calls external service , jndi lookup etc.

I would think i could refactor it like:

public class Singleton {
    private static Singleton instance;
    private Singleton(){
    }

    public synchronized static Singleton getInstance()
    {
        if(instance == null)
             instance = new Singleton();
        return instance;
    }

     //for the unit tests
     public static void setInstance(Singleton s)
     {
          instancce = s;
     }
}

The problem now is that just for unit testability I have forced the getInstance to be synchronized so just for testing aspect it will have a negative impact on the real application. Is there a way around it, it seems any other sort of lazy initialization will not work because of the broken nature of double locking pattern in java.

like image 561
bluphoenix Avatar asked Apr 30 '11 14:04

bluphoenix


People also ask

What is lazy initialization in Java Singleton?

Lazy initialization: In this method, object is created only if it is needed. This may prevent resource wastage. An implementation of getInstance() method is required which return the instance. There is a null check that if object is not created then create, otherwise return previously created.

Does Singleton allow lazy initialization?

Singleton Class in Java using Lazy LoadingThe instance could be initialized only when the Singleton Class is used for the first time. Doing so creates the instance of the Singleton class in the JVM Java Virtual Machine during the execution of the method, which gives access to the instance, for the first time.

What is lazy and early loading of Singleton and how will you implement it?

What is lazy and early loading of Singleton and how will you implement it in java? Both these refer to when the Singleton object gets created in the application. In lazy loading it is created only when the method creating the instance is first called. In early loading the instance is created once the class is loaded.

Is eager singleton thread-safe?

It is thread-safe even if we remove final from public static final Singleton instance = new Singleton (); . That's because the JVM guarantees that the instance will be created before any thread access the static instance variable.


1 Answers

You can use an enum as a Singleton

enum Singleton {
    INSTANCE;
}

Say your singleton does something undesirable in unit tests, you can;

// in the unit test before using the Singleton, or any other global flag.
System.setProperty("unit.testing", "true");

Singleton.INSTANCE.doSomething();

enum Singleton {
    INSTANCE;
    {
        if(Boolean.getBoolean("unit.testing")) {
           // is unit testing.
        } else {
           // normal operation.
        }
    }
}

Note: there is no synchronised blocks or explicit lock needed. The INSTANCE will not be loaded until the .class is accessed and not initialised until a member is used. provided you only use Singleton.INSTANCE and not Singleton.class there won't be a problem with the value used to initialise changing later.


Edit: if you use just the Singleton.class this might not initialise the class. It doesn't in this example on Java 8 update 112.

public class ClassInitMain {
    public static void main(String[] args) {
        System.out.println("Printing a class reference");
        Class clazz = Singleton.class;
        System.out.println("clazz = " + clazz);
        System.out.println("\nUsing an enum value");
        Singleton instance = Singleton.INSTANCE;
    }

    static enum Singleton {
        INSTANCE;

        Singleton() {
            System.out.println(getClass() + " initialised");
        }
    }
}

prints

Printing a class reference
clazz = class ClassInitMain$Singleton

Using an enum value
class ClassInitMain$Singleton initialised
like image 169
Peter Lawrey Avatar answered Oct 17 '22 00:10

Peter Lawrey