Java Singleton Design Pattern Best Practices with Bill Pugh Singleton Implementation


The implementation of Java Singleton pattern has always been a controversial topic among developers. 

Here we will check Bill Pugh Singleton Implementation.

But first what is Singleton Pattern? According to good programming practice:

  • Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
  • The singleton class must provide a global access point to get the instance of the class.
  • Singleton pattern is used for logging, drivers objects, caching and thread pool.
  • Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
  • Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.

Java Singleton Pattern Implementation

To implement a Singleton pattern, we have different approaches but all of them have the following common concepts.

  • Private constructor to restrict instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

Bill Pugh came up with a different approach to create the Singleton class using an inner static helper class. The Bill Pugh Singleton implementation goes like this:

Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.

This is the most widely used approach for Singleton class as it doesn’t require synchronization. I am using this approach in many of my projects and it’s easy to understand and implement also.

Bill Pugh Singleton Implementation


Go to source code

Comments

Popular posts from this blog

Debug Java Stream in Intellij Idea

Creating Efficient Docker Images with Spring Boot 2.3

CRUD Goes Even Easier With JPABuddy