epicGeek epicGeek - 3 years ago 85
Java Question

What is singleton pattern?Why and When should I use it?

I am a one and half year experienced java developer.
My question is :What is singleton? It seems that I never use it in my project(Java web,Spring boot ).
I just cannot understand why and when should I use singleton.
Sorry guys ,let me explain my confusion.
A simple singleton class look like this:

class Singleton {

private static Singleton instance;

private Singleton(){
}

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

return instance;
}
........
}


Looks like there is not difference when I want to new a singleton object:
Singleton s = new Singleton();

Answer Source

Singleton pattern gives you the control over the number of instances of the singleton class that can be instantiated. It is used numerous use cases.

The classic Java singleton looks just as you mentioned with a very important detail - the non public constructor.

The fact that the constructor is not public (either protected or private) will not allow anyone to create a new instance of singleton as you suggested:

Singleton singleton = new Singleton();

And that's the big difference than having just a regular class.

Note that such an implementation is not thread safe, and therefore you will either want to have it thread safe or non lazy initialized as follows:

  • Non lazy initialization

    public class Singleton {
        private static Singleton instance = new Singleton();
    
        private Singleton(){
        }
    
        public static Singleton getInstance(){
            return instance;
        }
    }
    
  • Thread safe

    public class Singleton {
        private static Singleton instance = null;
    
        protected Singleton() {
        }
    
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download