According to jls § 8.9.2 Enum Body Declarations
It is a compile-time error for an enum declaration to declare a finalizer. An instance of an enum type may never be finalized.
As finalizer executes just before Garbage Collector runs, if finalizer is not present does that means enum
type always remains loaded in memory, and Garbage Collector is not applicable on enum
type?
In my interpretation, the enum instances can be garbage collected (although as others have pointed out the circumstances that allow this to happen are a bit unusual), and as their finalize method is defined not to do anything, whether or not the finalize method is ever called is a moot point.
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
If you compile an enum like
enum Suit {SPADES, HEARTS, CLUBS, DIAMONDS}
You will see that the generated bytcodes (i.e. javap -p Suit
) correspond to a synthetic class:
final class Suit extends java.lang.Enum<Suit> { public static final Suit SPADES; public static final Suit HEARTS; public static final Suit CLUBS; public static final Suit DIAMONDS; private static final Suit[] $VALUES; public static Suit[] values(); public static Suit valueOf(java.lang.String); private Suit(); }
So, instances of the enum are static members of the class itself. Then I think the only way in which this could be garbage collected would be if the class itself is garbage collected, which is very unlikely to happen if it was loaded by the system class loader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With