How java ensures only one instance of an enum per JVM

风格不统一 提交于 2019-12-18 15:35:13

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/18471653/how-java-ensures-only-one-instance-of-an-enum-per-jvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!