DEV Community

Discussion on: Ways to create Singletons and the tradeoffs between them

Collapse
 
ujaehrig profile image
Ulf Jährig

Why is an enum not memory efficient (or less memory efficient than a class with a static member)? As far as I know the enum is implemented in Java as a class inheriting enum. Implementing a few methods (like valueOf() and values()) and the enum-values as static members. You won't say these two additonal methods are the inefficiency, do you?

BTW Joshua Block described in his book "Effective Java" the enum singleton as the preferred way to implement a singleton.

Also you should take a look at this article, as your double checking pattern is broken: cs.umd.edu/~pugh/java/memoryModel/...

Collapse
 
abh1navv profile image
Abhinav Pandey

Each enum instance takes as much memory as a normal object - methods do not matter...enum-values as static members is where the memory resides. Check this article for a comparison -
stackoverflow.com/questions/143285...

As for double checking - Can you get me the date on this article?

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

That article on double checked locking is extremely out-dated. It was written pre-Java 4. See the phrase "expected ... in 1.4." However, enough was known at the time of the then-upcoming JDK 5 that the authors also explain near the end the very simple way of getting double checked locking to work beginning with JDK 5. You need to declare the field as volatile.

So to fix your double checked locking example just declare instance as volatile.

Thread Thread
 
abh1navv profile image
Abhinav Pandey

thanks!

Collapse
 
ujaehrig profile image
Ulf Jährig

Methods will still take space in the permanent section of the heap, as classes are still loaded. But this is a one-time cost. But what should be the difference between a single static enum member and a static member in a normal class? IMHO it doesn't matter if the static member is part of an enum or part of a "normal" class. The only advantage of an non-enum is the possibility of lazy initialisation. So my suggestion would probably be more on the line of lazy initialisation required and not on memory consumption.

As Vincent already said, the article above is quite old (and volatile will help), but AFAIK the memory model didn't change and the overall problem is still valid today.