java如何确保每个JVM只有一个枚举的实例 [英] How java ensures only one instance of an enum per JVM

查看:137
本文介绍了java如何确保每个JVM只有一个枚举的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java如何在内部确保每个JVM只能存在一个ENUM实例?是否在应用程序启动时创建,当多个线程访问它时,它将只返回在启动时创建的对象?

或者实现类似于单例模式的某种双重同步即使多个线程访问它,只会创建一个元素?

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?

推荐答案

您可以在这个答案枚举实例是静态类字段,因此在第一次访问时初始化为加载类的一部分课程。

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)

这篇关于java如何确保每个JVM只有一个枚举的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆