jvmmetaspacestring-table

In jdk 1.8+, how metaspace layout the class info?


In jdk1.8+, when MetaspaceTest class is loaded into jvm, this is my understanding about the memory layout, is that right?

public class MetaspaceTest {
    /* 
     1. "a" would be interned into the global String Table of heap;
     2. object created by [new String("a")] would be placed in heap;
     3. constant STR_OBJ would be placed in the constant-pool of MetaspaceTest class info, 
        and pointing to the string object created by [new String("a")];
    */
    private final static String STR_OBJ = new String("a");
    /* 
     4. "b" would be interned in the global String Table of heap;
     5. static field literalStr would be placed in metaspace, 
       and pointing to the string "b" which is interned into the global String Table of heap;
    */
    private static String literalStr = "b";
    /*
     6. object created by [new Integer(8)] would be placed in heap;
     7. static field intNum would be placed in metaspace, 
       and pointing to the object created by [new Integer(8)];
    */
    private static Integer intNum = new Integer(8);
}

Solution

  • First of all, things like Metaspace and String Table are not specified in JLS or JVMS. It's exclusively an internal implementation detail of the particular JVM. For example, there are fully compliant JVM implementations that do not have Metaspace at all.

    If we talk about the modern HotSpot JVM, your understanding is not quite correct.

    1. No. An instance of java.lang.String object representing "a" is in Java Heap. The string table contains a reference to that object as long as "a" is strongly reachable.
    2. Yes.
    3. No. Run-Time Constant Pool holds things described in JVMS §4.4. Static fields belong to a class mirror, which is an instance of java.lang.Class in Java Heap.
    4. The same as 1.
    5. Metaspace (as the "meta" prefix suggests) contains the class metadata, but not the data itself. E.g. the metaspace includes the information that the class MetaspaceTest has a field named literalStr of type java.lang.String, but it has nothing to do with the value of that field.
    6. Yes.
    7. No. As written above, Metaspace contains only the description of fields, but not the data. The actual holder of instance fields is an object instance; the actual holder of static fields is a class mirror, i.e. the instance of java.lang.Class in the heap.