Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How java ensures only one instance of an enum per JVM

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?

like image 362
Victor Avatar asked Aug 27 '13 17:08

Victor


1 Answers

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)

like image 75
radai Avatar answered Oct 20 '22 04:10

radai