• Post Reply Bookmark Topic Watch Topic
  • New Topic

Enum Singleton  RSS feed

 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know how we can Enum as Singleton in Java ?
I want to know one sample class which showcases Enum as Singleton.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not an expert on such things, so maybe I just don't understand what you mean...

I don't think your question makes any sense. an ENUM is basically a way to list out a bunch of pre-defined values for a variable. For example, you may have a ENUM that lists out the days of the week.

Any place you use it, the values will be the same. So what would it mean for it to be a singleton? There's not really a state in an ENUM (that I am aware of) that could change...so I don't see what trying to make it into a singleton gives you...or really how it's not already behaving like one.

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use an enum to create a singleton, by making an enum with exactly one enum constant. For example:

I'm not a big fan of singletons. Some people regard singletons an anti-pattern - they can make code hard to test and cause code that uses them to have hidden dependencies, and they essentially create global variables, which are bad. If the singleton has mutable member variables, it's hard to make it thread-safe and if you do, you need to synchronize on the mutable state, which limits scalability.

I've worked on a project where there were singletons present in the code which we could not get rid of because the code of the new version of the product we were building needed to stay backward compatible with the old version. It was very hard to write automatic tests for this project, because the singletons could not be mocked for unit tests.

I've also worked on a project in which we had to use a calculation engine. The calculation engine consisted of a number of components which were all implemented as singletons. Those components had state. We wanted to make it multi-threaded but that was very hard because of the stateful singletons. There was simply no way to use the computation engine from multiple threads, so instead of having one multi-threaded process we ended up running multiple single-threaded processes on the server, which is much less memory-efficient.

So, it's good to understand the singleton pattern, but avoid using it if you can in real code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!