Singleton class in java

Singleton class in java

What is Singleton class in java? Have you used Singleton before?

Singleton is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it .And used to get free memory and total memory in Java.


Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java.

Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class. Since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application. If you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.

Write the code for a Singleton class in java ?

class Singleton {
    private static volatile Singleton instance = null;
  private Singleton(){}

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