The Wayback Machine - https://web.archive.org/web/20240717095731/https://www.geeksforgeeks.org/java-program-to-demonstrate-the-nested-initialization-for-singleton-class/
Open In App

Java Program to Demonstrate the Nested Initialization For Singleton Class

Last Updated : 07 Jan, 2021
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

A Singleton Class is capable of producing just a single instance. Every Singleton class has a getInstance method which returns its object. When the getInstance method is called for the first time, an object of the class is generated, stored, and then returned. On subsequent calls to getInstance, the same object generated earlier gets returned.

Nested Initialization can be used for making Singleton classes.
In the below implementation we are creating a Singleton class using Nested Initialization. Make the following observations:

  • The default no-arg constructor of this class is made private to prevent other classes from directly accessing it and making objects of Singleton.
  • The Singleton class has a static public getInstance method with Singleton as the return type. This will be used by other classes to get the object of Singleton.
  • There is a Nested class inside Singleton class. This Nested class has an Instance variable that stores the object of the Singleton class.
  • The getInstance method takes value from this Instance variable and returns it to the call site.

Demonstration of the creation of a Singleton class using Nested Initialization

Java




// Java Program to demonstrate Singleton Class
// using Nested Initialization
  
class Singleton {
  
    // a member variable
    String str = "GFG!";
  
    // Nested class has just 1 role i.e.creation of the
    // Singleton object and storing it in Instance variable
    private static class Nested {
        static Singleton Instance = new Singleton();
    }
  
    // The getInstance() method returns the object of
    // Singleton class stored in Instance variable
    public static Singleton getInstance()
    {
        return Nested.Instance;
    }
  
    // no-argument constructor has to be made private
    // this forces other classes to use getInstance() method
    // in order to obtain the instance of Singleton class
  
    private Singleton()
    {
        System.out.println("Object made");
    }
}
  
public class Main {
  
    public static void main(String[] args)
    {
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();
  
        // make changes to obj1.str and output obj2.str
        obj1.str = "geeksforgeeks!";
  
        System.out.println(obj2.str);
    }
}


Output

Object made
geeksforgeeks!

Advantages of Nested Initialization:

  • Lazy loading
  • Thread-Safety

Lazy loading:

  1. Lazy loading is simply postponing the object creation until it is actually needed.
  2. It results in increased performance as the overhead during program startup is reduced.
  3. In our case, the object of the Singleton class is not created until the getInstance method is called for the first time.

Thread-Safety: Thread-Safety is essential, else multi-threaded programs can yield unexpected random results.

  • A non Thread-Safe implementation of Singleton class 

Java




// Java Program to demonstrate need of Thread-Safety
  
class Singleton1 {
    static Singleton1 obj;
  
    private Singleton1()
    {
        System.out.println("Object made");
    }
  
    // This method returns obj
    // If both the threads enter getInstance simultaneously
    // then both see obj as null, hence 2 objects of
    // Singleton1 are created this defeats purpose of
    // Singleton class
    static Singleton1 getInstance()
    {
        if (obj == null)
            obj = new Singleton1();
  
        return obj;
    }
}
  
public class Main {
    public static void main(String[] args)
    {
  
        // Thread 1 will call getInstance
        Thread t1 = new Thread(new Runnable() {
            public void run()
            {
                Singleton1 a = Singleton1.getInstance();
            }
        });
  
        // Thread 2 will also call getInstance
        Thread t2 = new Thread(new Runnable() {
            public void run()
            {
                Singleton1 b = Singleton1.getInstance();
            }
        });
  
        // Start both the Threads
        t1.start();
        t2.start();
    }
}


Output

Object made
Object made
  • The Nested Initialization is thread-safe, this is because unlike the above implementation in Nested Initialization the getInstance method does not create an object, it simply returns it. The object is created when the Nested Class is initialized and this happens only once when the getInstance method is called for the very first time.

Thread-Safe implementation of Singleton class

Java




// Java Program to demonstrate Thread-Safety
// in NestedInitialization
  
class Singleton {
  
    private static class Nested {
        static Singleton Instance = new Singleton();
    }
  
    // This method returns Object, does not create it
    // Object is created on initialization of Nested class
    // which happens only once.
    public static Singleton getInstance()
    {
        return Nested.Instance;
    }
  
    private Singleton()
    {
        System.out.println("Object made");
    }
}
  
public class SingletonDemo {
    public static void main(String[] args)
    {
  
        // Thread 1 will call getInstance
        Thread t1 = new Thread(new Runnable() {
            public void run()
            {
                Singleton a = Singleton.getInstance();
            }
        });
  
        // Thread 2 will also call getInstance
        Thread t2 = new Thread(new Runnable() {
            public void run()
            {
                Singleton b = Singleton.getInstance();
            }
        });
  
        // Start both the Threads
        t1.start();
        t2.start();
    }
}


Output

Object made

Note: In the above implementation we have achieved thread-safety without using the synchronized keyword. This is a plus point since the synchronized keyword is known to affect performance noticeably.



Similar Reads

Java Program to Demonstrate the Double-Check Locking For Singleton Class
One of the key challenges faced by junior developers is the way to keep Singleton class as Singleton i.e. the way to prevent multiple instances of Singleton class. 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. In double-checked locking, code checks f
3 min read
Java Program to Demonstrate the Non-Lazy Initialization Thread-Safe
Java is one of the most popular Object-Oriented programming languages offered by Oracle which has a wide range of applications in website and application development explored by developers. Java along with some well-known and robust frameworks like Spring, Spring-Boot, etc. makes developer's life easy while developing/coding Software. Java offers 2
6 min read
Java Program to Demonstrate the Lazy Initialization Thread-Safe
Java is a popular object-oriented programming language used by developers and coders for website/app development. The creation of a class object using a new keyword is referred to as object instantiation. Java by default allows users to define two ways of object instantiation which are Eager and Lazy. Java Interpreter interprets program/script code
8 min read
Java Program to Demonstrate the Lazy Initialization Non-Thread-Safe
In recent years object-oriented programming has formed the pillars/bases of Website and Application (Software) Development. Java and Python are popular Object-Oriented programming languages out of which the former one is offered and maintained by Oracle, while the latter one is open-source. Java along with robust and easy-to-setup frameworks like s
8 min read
Difference Between Singleton Pattern and Static Class in Java
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object o
6 min read
Java Program to Demonstrate How User Authentication is Done
Authentication is the process of verifying the identity of users or information. User authentication is the process of verifying the identity of the user when that user logs in to a computer system. The main objective of authentication is to allow authorized users to access the computer and to deny access to unauthorized users. Example Default Assu
2 min read
Java Program to Demonstrate the Call By Value
Functions can be summoned in two ways: Call by Value and Call by Reference. Call by Value method parameters values are copied to another variable and then the copied object is passed, that's why it's called pass by value where actual value does not change User cases: Calling methods in programming where the method needs to be called for using its f
3 min read
Singleton Class in Android
The Singleton Pattern is a software design pattern that restricts the instantiation of a class to just "one" instance. It is used in Android Applications when an item needs to be created just once and used across the board. The main reason for this is that repeatedly creating these objects, uses up system resources. The identical object should ther
4 min read
JDBC Using Model Object and Singleton Class
This article explains how to perform JDBC operation using a Model object and a Singleton connection class from a MySQL database . JDBC is an Application Programming Interface for Java which connects a Java application with a database to perform CRUD operations. Pre requisite: JDK 7+ (Click here to download)MySQL Database (Click here to download)MyS
6 min read
Singleton and Prototype Bean Scopes in Java Spring
Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be instantiated, how long does that object live, and how many objects will be created for that bean throughout. Basically, it controls the instance creation of the bean and it is managed by the spring container.Bean Scopes in Spring The spring framework provides fiv
8 min read
three90RightbarBannerImg