Is enum Really Best Singletons?

You must have heard multiple times that enum are always the best choice for implementing singleton design pattern in java. Are they really best? If it is then how it is better than other available techniques? Let’s find out.

Writing a singleton implementation is always tricky. I discussed already couple of methods (including my favorite method as well) in my this blog post. I have written there clearly that enums provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort.

Problems with enum as singleton

Having said that, like with any other thing in the universe, this approach does have it’s disadvantages which you will need to consider before making any decision.

  1. By default, enums do not support lazy loading.
  2. Though it’s very very rare but if you changed your mind and now want to convert your singleton to multi-ton, enum would not allow this.

If above both cases are no problem for anybody, the enum is probably the best choice.

Anyways, on side note, after compilation java enums are converted to classes only with additional methods e.g. values() and valueOf()… etc.

enum based singleton example

Once you have decided to write enum based singleton, writing it is really easy e.g.

enum Singleton
{
	INSTANCE;
	// instance vars, constructor

	private final Connection connection;
	
	Singleton()
	{
		// Initialize the connection
		connection = DB.getConnection();
	}

	// Static getter
	public static Singleton getInstance()
	{
		return INSTANCE;
	}

	public Connection getConnection()
	{
		return connection;
	}
}

Now you use can use final Singleton s = Singleton.getInstance(). Remember that since this is an enum you can always access this via Singleton.INSTANCE as well.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

4 thoughts on “Is enum Really Best Singletons?”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.