I have this singleton class

public final class MySingleton{
    public static MySingleton singletonInstance;

    private MySingleton(){}

    static{
       singletonInstance=new MySingleton();
    }

    public static MySingleton getInstance(){
       return singletonInstance;
    }

}

I wanted to know is there any other simpler and better way of creating a singleton instance?

the most used way (in code that I've seen so far) is a bit different. also, I would keep the instance as a private variable.

public class MySingleton{
  private static MySingleton instance = null;

  private MySingleton(){

  }

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

Yes, keeping the variable private is a good idea, but stultuske's version is not thread safe, whereas the original version and the enum version are both thread safe.

well... personally haven't worked much on applications that required Singletons, and was only talking about those :)

This question has already been answered. Start a new discussion instead.