Monday, 25 September 2017

Design Patterns | Bill Pugh Singleton Implementation

Prior to Java 5, Java memory model had a lot of issues and above approaches used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously. So Bill Pugh came up with a different approach to create the Singleton class using an inner static helper class.

The Bill Pugh Singleton implementation

public class Singleton {
             * Bill Pugh Singleton Pattern
             * Bill Pugh Singleton Pattern is the most widely used approach for
             * Singleton class as it doesn’t require synchronization
            private Singleton() {

            private static class SingletonHolder {
                        private static final Singleton INSTANCE = new Singleton();

            public static Singleton getInstance() {
                        return SingletonHolder.INSTANCE;

With using the private inner static class the holder is not loaded to memory until someone call the Instance method. Bill Pugh solution is Thread safe and it doesn't require synchronization.
Related Posts Plugin for WordPress, Blogger...