How does Java ensure internally that only one instance of an ENUM would exist per JVM? Is it created when application boots up and from that point on when multiple threads access it, it will just return the object created at startup?
Or does it implement some kind of double synchronization similar to the singleton pattern so that even if multiple threads access it, only one istance will be created?
Asked
Active
Viewed 4,631 times
11

Victor
- 16,609
- 71
- 229
- 409
-
1It ensures one instance per class loader. If you have multiple class loaders, each one can have their own instances. They are created on demand. (Lazy-loaded) The JVM has its own mutex lock for this. – Peter Lawrey Aug 28 '13 at 06:46
2 Answers
7
as you can read in this answer enum instances are static class fields and so are initialized as part of class loading when you 1st access the class.
classloading is synchronized internally so that ensures enum instances are singletons (singletons within the same classloader, that is. if you have the same enum loaded by multiple loaders you will get multiple instances)
-
Thanks. Are the same true for normal static variables ? i.e a static variable is in danger of being initilaized multiple times by multiple classloaders? – Victor Aug 27 '13 at 17:24
-
1@Victor - yes. you wont see it im plain old java programs, but its a common issue with more complex systems like j2ee where you have multiple classloaders – radai Aug 27 '13 at 17:27
-
@Victor Static initializations are performed within the context of a classloader. In the case of having multiple classloaders (isolated, for example in J2EE), they'll be loaded multiple times as long as those very classloaders are isolated and do not converge in any level of their hiearachy where the class could have been loaded (since requesting a load would mean returning something in the cache of a common parent classloader). – Fritz Aug 27 '13 at 17:28
-
@Gamb - or fi the class in question is found in multiple jars along the classloader tree - common when someone includes a library in a deployment-specific /lib and in some higher-up global /lib. the classloaders dont have to be completely separate for this to happen – radai Aug 27 '13 at 17:30
-
@radai I was addressing the normal behaviour, if the developer choses to deploy fat WARs it is a discussion for another question :). Still, you're right about it, but it wouldn't be a cause related to classloading per se but to a human error. – Fritz Aug 27 '13 at 17:35
3
Enum instances are created at class loading time. If the same enum gets loaded by more than one classloader (when classloading games are being played by, for example, a web app container), you will have multiple incompatible instances in memory.

Jim Garrison
- 85,615
- 20
- 155
- 190
-
-
@apersiankite It means that the instances look the same, but test: `enum1.getClass() == enum2.getClass()` return false. They are in fact different classes for JVM. – Michał Zabielski Mar 25 '18 at 22:19