Java枚举实例的生命周期 [英] Life span of a Java enum instance
问题描述
我知道每个枚举类型的预定义常量只有一个实例。这样还对吗现在,假设有一个称为枚举的 value
的实例变量,并且假设 ONE
是预定义的常量。如果为 ONE 的实例修改了
value
,则这会影响所有引用的变量一个
。但是,当垃圾回收器摆脱了枚举的所有实例时, value
的值会怎样?
I understand there is one single instance per predefined constant of an enum type. Is that even right? Now, suppose there is an instance variable called value
of the enum, and suppose ONE
is a predefined constant. If value
is modified for (the) instance of ONE
then this affects all variables referring to ONE
. But what happens to the value of value
when the garbage collector gets rid of all instances of the enum? Do they ever get thrown away even?
示例
这是一个简单的例子吗?例如,有两个变量 A
和 B
,均引用 ONE
。 value
的值在第一次使用 B
之前取反。如果垃圾收集器在行 Number B = Number.ONE;
之前删除了 ONE
的实例,则我想,值
的值将被重置为1。
Here is a simple example where there are two variables A
and B
, both referring to ONE
. The value of value
is negated before B
is used for the first time. If the garbage collector had gotten rid of the instance of ONE
before the line Number B = Number.ONE;
, then the value of value
would have been "reset" back to 1, I presume. Is this correct?
枚举:
public enum Number
{
ONE(1), TWO(2), THREE(3);
int value;
Number(int value) { this.value = value; }
void negate() { value = -value; }
@Override
public String toString() { return "value: " + value; }
}
主要方法:
public static void main(String[] args)
{
Number A = Number.ONE;
A.negate();
Number B = Number.ONE;
System.out.println(A + " " + B);
}
输出:
值:-1值:-1
value: -1 value: -1
所以我的问题是,输出是否可以是以下内容(如果说 A = null;
在使用 B
之前被添加)?
So my question is, can the output ever be the following (if say A = null;
is added before B
is used)?
值:-1值:1
value: -1 value: 1
推荐答案
枚举是隐式的公共静态最终变量
字段,因此它们永远不会被垃圾回收。
Enums are implicitly public static final
fields, so they are never garbage collected.
EDIT
正如@RealSkeptic的评论所指出的那样,在具有多个类加载器的jvm实例中,事情要复杂一些。然后,当静态字段值的类时,它们可能会消失会被卸载。
As kindly pointed out in the comments by @RealSkeptic, things are a little bit more complex in a jvm instance with multiple class loaders. Then static field values may disapear when their classes are unloaded.
但是,默认情况下,只要jvm实例处于活动状态,只有一个类加载器处于活动状态,因此在示例应用程序中永远不会发生静态字段被垃圾回收的情况。
However, by default, there is only one class loader which is alive as long as the jvm instance is alive, so in your example application it can never happen that static fields are garbage collected.
这篇关于Java枚举实例的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!