The method area, like the heap, is an area of memory shared by threads and used to store data such as class information that has been loaded by the virtual machine, just-in-time compiled code, static variables, and constants.
According to the Java Virtual Machine specification, an OutOfMemoryError is thrown when a method area cannot meet its memory allocation requirements. Although the specification states that a virtual machine may not implement garbage collection because the method area is too inefficient compared to the heap’s garbage collection efficiency, this part of the memory area can be reclaimed.
There are two main types of garbage collection in the method area, namely, the collection of discarded constants and the collection of useless classes.
When a constant object is no longer referenced anywhere, it is marked as a deprecated constant and can be reclaimed.
A class in a method area must meet all three of the following criteria to be marked as useless:
1. The Java heap does not have any instance objects of this class.
2. The classloader that loaded the class has been reclaimed.
3. The java.lang.Class object corresponding to this Class is not referenced anywhere, and the methods of this Class cannot be accessed anywhere through reflection.
Classes that meet the above three criteria can be recycled, but not always. The HotSpot virtual machine provides the -xnoclassGC parameter to control whether or not to recycle.