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 !!

Leave a Reply

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial