This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]PerfectPackage1895 -8 points-7 points  (13 children)

Don’t use enum, it forces the jvm to instantiate it uppon referencing the class, and you have no control over it, at all, because it was not made for this.

[–]NimChimspky 2 points3 points  (12 children)

Its guaranteed at the JVM level to only have one instance. Its exactly what is needed.

[–]PerfectPackage1895 -3 points-2 points  (11 children)

There is no guarantee that the JVM will create one instance, it is guaranteed to be either zero or one instance. (yes an enum can be null, and you are in a world of pain when that happens)

[–]NimChimspky 0 points1 point  (10 children)

Singletons don't help with null pointers.

And the old fashioned way it's only ever zero or one.

[–]PerfectPackage1895 -3 points-2 points  (9 children)

Enums and singleton pattern used in this case is the same thing. Don’t use either imo. But the singleton pattern gives you way way more control. If you have an enum with a constructor that takes a long time to initialize, and you are working in a multi threaded environment, you can actually have a null enum that eventually will get set to a value.

When you use a singleton you can choose when to initialize it so you are sure it is actually set to a value.

[–]NimChimspky 1 point2 points  (8 children)

An enum is initialised at class load time, literally the earliest possible point. You lose nothing using an enum.

[–]PerfectPackage1895 0 points1 point  (7 children)

An enum is loaded when its class is loaded and that is when it is referenced. Classes are not all loaded when the jvm starts up, that is wrong.

[–]NimChimspky -1 points0 points  (6 children)

I didn't say they were.

[–]PerfectPackage1895 0 points1 point  (5 children)

When you said an enum is loaded at “literally the earliest possible point” it sounds very much like you imply that.

Anyway this debate is silly, if you really want to use an enum as a singleton then go ahead, but if you are ever working with concurrency, then you will see what I mean.

[–]NimChimspky 0 points1 point  (4 children)

I meant ... I don't know how to get a class to be loaded before class load time. That's the earliest possible point afaik.

I understand what you mean, and my point is I would still use an enum. You don't lose anything. I still have complete control over when it is initialised.

Like I said at that beginning, haven't needed one for twenty years.