how to create a singleton java code example

Example 1: java singleton implementation

public class SingletonClass {
    private static final SingletonClass SINGLE_INSTANCE = new SingletonClass();
    private SingletonClass() {}
  public static SingletonClass getInstance() {
      return SINGLE_INSTANCE;
    }
}

Example 2: java singleton

public final class SomeSingleton {
   public static final SomeSingleton INSTANCE;

   private SomeSingleton() {
      INSTANCE = (SomeSingleton)this;
      System.out.println("init complete");
   }

   static {
      new SomeSingleton();
   }
}

Tags:

Java Example