gleery gleery - 1 month ago 6
Java Question

Different ways to write singleton in Java

The classic of writing a singleton in java is like this:

public class SingletonObject
{
private SingletonObject()
{
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}


and we can add synchronized keyword if we need it to run in multithreaded cases.

But I prefer to write it as:

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
return ref;
}

private static SingletonObject ref = new SingletonObject();
}


which I think is more concise, but strangely I didn't see any sample code written in this way, is there any bad effects if I wrote my code in this way?

Answer

The difference between your code and the "sample code" is that your singleton is instantiated when the class is loaded, while in the "sample" version, it is not instantiated until it is actually needed.