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.
- By default, enums do not support lazy loading.
- 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 !!
Jimis
How do you reach this conclusion: “enums do not support lazy loading.” What about people saying enum is laizy loaded as found in https://stackoverflow.com/questions/15470433/single-element-enum-type-singletone-with-lazy-loading-capability/15470565#15470565 , https://stackoverflow.com/questions/5842273/java-lazy-initializing-singleton/5843514#5843514 and https://stackoverflow.com/questions/16771373/singleton-via-enum-way-is-lazy-initialized/16771449#16771449
Lokesh Gupta
Thanks for the feedback. Probably, I should say “by default”. Edited the post.
Ravinder
connection = DB.getConnection(); unable to understand what is DB here .this is a class or an interface
not me
3. you can’t create subclasses of an enum-based singleton