Search code examples
javajvmbytecode

How does JVM deal with dynamic classes


Class definitions are stored in the Method Area, as the Java Virtual Machine Specification says (The Java® Virtual Machine Specification Java SE 7 Edition):

The method area is created on virtual machine start-up. Although the method area is logically part of the heap, simple implementations may choose not to either garbage collect or compact it.

As we know, some bytecode tools like ASM, cglib, javassist, Hibernate and Spring frameworks are using them. For a common class file, JVM loads and parses and initializes and finally uses it, I am confused about how does JVM deal with the classes generated by bytecode tools dynamically. My questions are:

  1. If JVM loads, parses and initializes the dynamic classes as the common class file?

  2. Are they stored in the Method Area as well?

  3. How does JVM unload and clean the dynamic class definitions to prevent itself from occurring an OutOfMemoryError?


Solution

  • All class are loaded at runtime, possibly compiled to native code. As such there is nothing special about class generated after the program has started.

    If JVM loads, parses and initializes the dynamic classes as the common class file?

    It loads the same way as class which existed when the program started.

    Are they stored in the Method Area as well?

    They are stored the same way in fact it is hard to tell if a class is dynamic or not.

    How does JVM unload and clean the dynamic class definitions to prevent itself from occurring an OutOfMemoryError?

    The JVM can unload classes when the ClassLoader they are in is unloaded. This is true whether the classes are dynamic or not.

    how could the JVM know to treat dynamic classes any differently than 'normal' classes?

    There is one example of dynamic classes which are special. These are the lambda classes which are generated at runtime. What makes them different is they are not bound to a class loader, they don't even have a normal class name. They get unloaded when all the instances of that class are unused.

    From InnerClassLambdaMetafactory

    UNSAFE.defineAnonymousClass(targetClass, classBytes, null);
    

    The class has no class name attached to it (nor a ClassLoader)