Java enum instance lifetime

I understand that there is one instance per predefined enum type constant. Is that even right? Now suppose that there is an instance variable called valueenumerations, and suppose that it ONEis a predefined constant. If valuemodified for () the instance ONE, then this affects all variables related to ONE. But what happens to the value valuewhen the garbage collector gets rid of all the enumeration instances? Are they ever thrown away even?

Example

Here is a simple example where there are two variables Aand B, both of which refer to ONE. The value valueis canceled before being used Bfor the first time. If the garbage collector got rid of the instance ONEbefore the row Number B = Number.ONE;, then the value valuewould be "reset" back to 1, I suppose. Is it correct?

Listing:

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; }
}

The main method:

public static void main(String[] args)
{
    Number A = Number.ONE;
    A.negate();
    Number B = Number.ONE;

    System.out.println(A + "   " + B);
}

Conclusion:

value: -1: -1

So my question is: can the conclusion ever be as follows (if I say that it was A = null;added before use B)?

value: -1 value: 1

+4
source share
2 answers

Enumerations are implicitly public static finalfields, so they are never collected by garbage.

EDIT

@RealSkeptic, jvm- , . , .

, , jvm , , .

+3

:

public enum FooEnum {
  CONST
}

- :

Compiled from "FooEnum.java"
public final class FooEnum extends java.lang.Enum<FooEnum> {
  public static final FooEnum CONST;

  static {};
    Code:
       0: new           #1                  // class FooEnum
       3: dup
       4: ldc           #12                 // String CONST
       6: iconst_0
       7: invokespecial #13                 // Method "<init>":(Ljava/lang/String;I)V
      10: putstatic     #17                 // Field CONST:LFooEnum;
      13: iconst_1
      14: anewarray     #1                  // class FooEnum
      17: dup
      18: iconst_0
      19: getstatic     #17                 // Field CONST:LFooEnum;
      22: aastore
      23: putstatic     #19                 // Field ENUM$VALUES:[LFooEnum;
      26: return

  public static FooEnum[] values();
    // elided

  public static FooEnum valueOf(java.lang.String);
    // elided
}

CONST - , .

, .

Java, Java SE 8 Edition 8.9. :

, , . , (§15.9.1).

, , enum :

Enum , .

.

, .

+2

All Articles