<

Use Lazy Initialization in singleton pattern

Published on
16,335 Points
5,435 Views
9 Endorsements
Last Modified:
Awarded
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing instance is used.
public class MySingletonClass {
    private static MySingletonClass instance; 

    private MySingletonClass(){
      //private constructor to prevent extra instantiation
    }

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

    // rest of MySingletonClass's methods... 
}

Open in new window


However, this approach has the potential of not working in multi-threaded programs. If two different threads simultaneously invoke your method (i.e., getInstance()), they would most likely create two different instances while you expected that object to create only once across your application. Another method to evade this problem is "double-checked locking", which is rejected now and won't work properly as well.

Here is an example of the double-checked locking method for your reference:
public class MySingletonClass {
    private static MySingletonClass instance; 

    private MySingletonClass(){
      //private constructor to prevent extra instantiation
    }

    public static MySingletonClass getInstance(){
        if(instance == null) {
           synchronized(MySingletonClass.class){
               if(instance == null){
                   instance = new MySingletonClass();
               }
           }
        }
        return instance;
    }

    // rest of MySingletonClass's methods... 
}

Open in new window



Fortunately, this article will show you how to get around this problem using the following steps:

1. Define a static inner class


First define a static inner class and make it private. For example LazyInitializer, and then put the "instance" field into it. Then you have to initialize the instance in declaration.
//Lazy initializing method
public class MySingletonClass { 
    private static class LazyInitializer {
        private static MySingletonClass instance = new MySingletonClass();
    }
}

Open in new window


2. Create getInstance() method


Now create the instance method as below:
public static MySingletonClass getInstance(){
   return LazyInitializer.instance;
}

Open in new window


3. If your instance needs to be initialized


In this case use a static block inside the inner class:

public class MySingletonClass {
     
    private static class LazyInitializer{
         private static MySingletonClass instance = new MySingletonClass();
         static {
             instance.setMyParam("A_PARAM_VALUE");
         }
    } 
}

Open in new window


4. Put it altogether


This is the whole snippet:
//Lazy initializing method
public class MySingletonClass {
 
    private MySingletonClass(){
      //private constructor to prevent extra instantiation
    } 
    private static LazyInitializer {
         private static MySingletonClass instance = new MySingletonClass();
    } 
    public static MySingletonClass getInstance(){
        return LazyInitializer.instance;
    }
    // rest of MySingletonClass's methods... 
}

Open in new window



Editor's Note: for those new to Java programming or to using design patterns such as Singletons, I can atest to the frequency in which I personally use this construct. Consequently, with the increasing need for concurrency in applications, I strongly recommend you internalize the above information and any additional research you may need to fully grasp the concept. Therefore, this is short and sweet, but great knowledge as you embark as a Java developer!
9
Author:mnrz
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free