Interview Questions, Tips and Tricks, Tutorial

Singleton in Java

What is Singleton?

Singleton is a class that cannot have more than one instance.
(Source: https://en.wikipedia.org/wiki/Singleton_pattern)

In Java, there are many way to create singleton class, one of the example is:

class SingletonClass {

    private static volatile SingletonClass INSTANCE = null;

    private SingletonClass() {   }

    public SingletonClass getInstance() {
         if (INSTANCE == null) {
            synchronized (SingletonClass.class) {
                 if (INSTANCE == null) {
                    INSTANCE = new SingletonClass();
                 }
            }
         }
         return INSTANCE;
    } 
}

When to use singleton?

Singleton is used when you need system wide “global value” that need to be accessed by many part of systems. Example: Session Value, Logger, Cache, etc

Advertisements