Other Ways of Singleton in Java

Here's one more way to do it :

public enum Singleton{
  INSTANCE("xyz", 123);

  // Attributes
  private String str;
  private int i;

  // Constructor
  Singleton(String str, int i){
    this.str = str;
    this.i = i;
  }
}

According to Josh Bloch's Effective Java, this is the best way to implement Singleton in Java. Unlike implementations that involve a private static instance field, which can be multiply instantiated through the abuse of reflection and/or serialization, the enum is guaranteed to be a singleton.

The main limitation with enum singletons is that they are always instantiated at class loading time and can't be lazily instantiated. So if, for example, you want to instantiate a singleton using run-time arguments, you'll have to use a different implementation (preferably using double-checked locking).


No, it is not. You didn't declare myClass private static final, nor the getInstance() is static. The code also doesn't really compile.

Here's the Singleton idiom:

public class MyClass {
    private static final MyClass myClass = new MyClass();

    private MyClass() {}

    public static MyClass getInstance() {
        return myClass; 
    }
}

It should be private, so that nobody else can access it directly. It should be static so that there's only one of it. It should be final so that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don't need to worry (that much) about threading.

If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:

public class MyClass {
    private MyClass() {}

    private static class LazyHolder {
        private static final MyClass myClass = new MyClass();
    }

    public static MyClass getInstance() {
        return LazyHolder.myClass;
    }
}

You should however put big question marks whether you need a Singleton or not. Often it's not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.