Singleton

This lesson discusses all the different ways of creating singleton objects in Java.

We'll cover the following...

Question # 1

What is the singleton pattern?

The singleton pattern is applied when we want to restrict instantiation of a class to single instance. This is one of the very common Java interview questions asked. There are several finer points to consider when evaluating the different alternatives for creating singleton objects in Java. For this question, let's assume you are designing a game and want to model the Superman character through the Superman class. There can only be one Superman so you want to ensure that only a single instance of the class ever exists. We also need to consider if the singleton class will be accessed in a multi-threaded environment or not.

  • The easiest way to create a singleton is to mark the constructor of the class private and create a private static instance of the class that is initialized inline. The instance is returned through a public getter method. The drawback of this approach is if the singleton object is never used then we have spent resources creating and retaining the object in memory. The static member is initialized when the class is loaded. Additionally, the singleton instance can be expensive to create and we may want to delay creating the object till it is actually required.

    Singleton eager initialization

    public class Superman {
        private static final Superman superman =  = new Superman();
    
        private Superman() {
        }
    
        public static Superman getInstance() {
            return superman;
        }
    }
    

    A variant of the same approach is to initialize the instance in a static block.

    Singleton initialization in static block

    public class Superman {
        private static Superman superman;
    
        static {
            try {
                superman = new Superman();
            } catch (Exception e) {
                // Handle exception here
            }
        }
    
        private Superman() {
        }
    
        public static Superman getInstance() {
            return superman;
        }
    }
    
    

    The above approach is known as Eager Initialization because the singleton is initialized irrespective of whether it ...