Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Garbage Collector run on Enum type?

Tags:

java

enums

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?

like image 382
Vishrant Avatar asked May 07 '14 18:05

Vishrant


People also ask

Are enums garbage collected?

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.

What is an enum in java?

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.


1 Answers

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.

like image 97
Edwin Dalorzo Avatar answered Sep 21 '22 12:09

Edwin Dalorzo