The eager singleton

As mentioned in this post singletons can be instantiated in two different ways, and one of them is eager instantiation.

Bellow we have an example of a class defining a singleton that will be eager instantiated.

EagerSingleton.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package Singleton.eagersingleton;

public class EagerSingleton {

private static final EagerSingleton Instance = new EagerSingleton();

private EagerSingleton() {}

public static EagerSingleton getInstance() {
return instance;
}

public void doSomeWork() {
System.out.println("EagerSingleton is doing some work\n");
}
}

In the above example, an instance of this object is created as soon as the JVM loads the class, so we should only use it if the needed computational resources are not extremely high. If they are, and we still believe that a singleton is the best option, than we should opt for the lazy instantiation.

what is going on in this class ?

As soon as the class is loaded the final attribute instance is instantiated in line 5.

In line 7 we define the class constructor as private. This will prevent client code to instantiate the object via the new keyword. Due to this private constructor is not possible to use EagerSingleton egSingleton=new EagerSingleton.

in order to get our instance we will need to call the static method on line 9, and that will return us the singleton object (which has been initialized at class loading time).

After receiving an instance of the object, we can call all the public methods on it.

An example for the code in this article can be found in git-hub

Happy coding.

Share