Describe Eager Initialization of Singleton Pattern

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class. For Runtime class Java uses these approach.
Here is the implementation of static initialization singleton class.


package java.lang;

import java.io.*;
import java.util.StringTokenizer;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;

/**
* Every Java application has a single instance of class
* <code>Runtime</code> that allows the application to interface with
* the environment in which the application is running. The current
* runtime can be obtained from the <code>getRuntime</code> method.
* <p>
* An application cannot create its own instance of this class.
*
* @author unascribed
* @see java.lang.Runtime#getRuntime()
* @since JDK1.0
*/

public class Runtime {
private static Runtime currentRuntime = new Runtime();

/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
    //... Other code continued ..

The problem with this approach is, its creates the instance when the class loader is loading classes. So if your Singleton is using a lots of resources then it is degrading the system performance by eagerly loading the resources when it is not required. The resources should be loaded when it is requested by the client for first time. And by virtue Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method. For solution  we will look in the next section : Lazy Initialization of Singleton classes.

core java 12 Creational-Pattern 12

FOLLOW US ON LinkedIn



Explore Tutu'rself