directory

  • 1. The description of the JVM
  • 2. Class loading subsystem
  • 3. Run time data area
  • 4. Vm stack
  • 5. The heap area
  • 6. Method of area
  • 7. Object instantiation and memory access
  • Overview of garbage collection
  • 9. Classic garbage collector
  • 10. The G1 and ZGC

1. Concept of method area

The method area mainly stores type information, constants, static variables, and just-in-time compiler code cache

The Method Area, like the Java heap, is an Area of memory shared by threads

2. The method area is created at JVM startup, and its actual physical memory space can be as discontinuous as the Java heap area

The size of the method area determines how many classes the system can hold. If the system defines too many classes and causes the method area to overflow, the vm will also throw an overflow error: Java. Lang. OutOfMemoryError: PermGen space or Java. Lang, OutOfMemoryError: Metaspace, such as:

  • Load a large number of third-party JAR packages;
  • Too many Tomcat projects are deployed.
  • A large number of dynamically generated reflection classes;

4. Shutting down the JVM frees memory in this area.

2. Evolution of method area

In JDK7 and before, it was customary to call a method area a permanent generation. Starting with JDK8, permanent generations are replaced with meta-spaces.

In essence, method blocks and permanent generations are not equivalent. Only for hotSpot. The Java Virtual Machine Specification does not have uniform requirements on how to implement the method area.

  • Disadvantages of using permanent generation: Using JVM memory, resulting in Java programs that are easier to OOM(exceeding the -xx :MaxPermSize limit).

  • In JDK8, the concept of permanent generations is finally scrapped completely, and replaced with Metaspace, which is implemented in local memory as in JRockit and J9. Metaspace is essentially an implementation of the method area in the JVM specification. However, the biggest difference between the meta-space and the permanent generation is that the meta-space is not in the memory set by the VM, but in the local memory (PC memory).

It’s not just the names of the permanent generations and metacases that have changed. The internal structure has also been adjusted. According to the Java Virtual Machine Specification, if the method area cannot meet the new memory allocation requirements, an OOM exception is raised.

2.1 Changes in method area

Changes to the method area in HotSpot:

In JDk1.6 and earlier, there were permanent generations, where static variables were stored

Jdk1.7 has persistent generation, but is progressively de-perpetuated, string constant pools, static variables removed, and stored in the heap

In JDK1.8 and beyond, there are no persistent generations. Type information, fields, methods, constants are stored in the local memory meta-space, but the string constant pool, static variables are still in the heap

Methods area Constant pool Run-time constant pool A static variable
Jdk6 and previous permanent generation Methods area Methods area Methods area
Jdk7 and previous permanent generation Methods area The heap The heap
Jdk8 and previous meta Spaces Methods area Methods area The heap

2.2 Reasons for the change

With the advent of Java8, persistent generations are no longer seen in HotSpot VM. But that doesn’t mean classes. The metadata information of the. This data is moved to an area of local memory not connected to the heap, called Metaspace. Since the metadata of a class is allocated in local memory, the maximum allocatable space of the metadata space is the memory space available to the system. This change was necessary for the following reasons:

  • 1. Because the size of the permanent generation setting space is difficult to determine. In some scenarios, if there are too many dynamically loaded classes, it is easy to produce O0M of the Perm area (permanent generation). For example, in a practical Web project, because there are many function points, many classes need to be dynamically loaded during operation, and fatal errors often occur."The Exception in the thread 'dubbo client 7.0.x.x connector' Java lang. OutOfMemoryError: PermGenspace"The biggest difference between a meta-space and a permanent generation is that the meta-space is not in the virtual machine, but uses local memory. Therefore, by default, the size of the meta-space is limited only by local memory.
  • 2. Tuning persistent generations is difficult.

3. Internal structure of the method area

In understanding the Java VIRTUAL Machine, the method area store is described as follows: It is used to store type information that has been loaded by the virtual machine, constants, static variables, and code cache compiled by the just-in-time compiler.

3.1 Type Information

For each loaded type (class, interface, enum, annotation), the JVM must store the following type information in the method area:

  • The permission class name for this type (full name = package name). The name of the class)
  • The full valid name of the type’s immediate parent (no parent for interface or java.lang. Object)
  • Modifiers of this type (some subset of public, abstract, final)
  • An ordered list of direct interfaces of this type

3.2 Domain Information (Member Variables)

The JVM must keep information about all fields of the type and the order in which the fields are declared in the method area.

Domain information includes domain name, domain type, and domain modifiers (public, private, protected, static, final, volatile, transient).

3.3 Method Information (Method)

The JVM must hold the following information about all methods, including the declaration order, as well as domain information:

  • Method name.
  • Method return type (or void).
  • The number and type of method arguments (in order).
  • Method modifiers (a subset of public, private, protected, static, final, synchronized, native, abstract).
  • Methods bytecodes, operand stack, local variable table and size (except abstract and native methods).
  • Exception table (except for abstract and native methods), the start and end location of each exception handler, the offset address of the code handler in the program counter, and the constant pool index of the caught exception class.

3.4 Non-final Class Variables (static variables that are not declared final)

Static variables are associated with the class and are loaded as the class is loaded; they become a logical part of the class data

A class variable is shared by all instances of the class, and you can access it even if there is no instance of the class. The following code does not report a null pointer exception:

public class MethodAreaTest {
    public static void main(String[] args) {
        Order order = null; order.hello(); System.out.println(order.count); }}class Order {
    public static int count = 1;
    public static final int number = 2;

    public static void hello(a) {
        System.out.println("hello!"); }}Copy the code

3.5 constant values

Class variables declared final are handled differently, with each global constant assigned at compile time.

Review:

1. Clinit () is the class or interface Initialization method. Note that it is not the constructor init().

2. This method does not need to be defined and is a combination of the statements in the static code block and the assignment actions that the Javac compiler automatically collects for all class variables in the class.

3. If there were no static variables, there would be no Clinit methods in the bytecode file

3.6 constant pool

  • A valid bytecode file contains the Constant Poo1 Table, which contains literals and symbolic references to type fields and methods, in addition to the version information, fields, methods, and interface descriptions of the class.
  • A Java source file of classes, interfaces, compiled to produce a bytecode file. Bytecodes in Java require data, usually too large to be stored directly in bytecodes, or in a constant pool; This bytecode contains a reference to the constant pool. Runtime constant pools are used for dynamic linking.
  • For example, the following code, although only 194 bytes, uses string, System, Printstream, and Object structures.
Public class Simpleclass {
public void sayhelloo(a) {
    System.out.Println (hello) }
}
Copy the code
  • The constant pool structure in bytecode can be viewed as a table from which virtual machine instructions find the class names, method names, parameter types, literals, and other information to be executed.

3.7 Runtime constant pool

  • The Runtime Constant Pool is part of the method area. Used to hold the reference information needed for each class to run

  • The Constant Pool Table is the part of the Class file that stores literal and symbolic references generated at compile time and is stored in the runtime Constant Pool in the method area after the Class is loaded.

  • Runtime constant pool, which is created after classes and interfaces are loaded into the VIRTUAL machine.

  • The JVM maintains a constant pool for each loaded type (class or interface). Data items in a pool, like array items, are accessed by index.

  • The runtime constant pool contains a variety of constants, from numeric literals that are explicit at compile time to method or field references that are not available until they are parsed at run time. So instead of having a symbolic address in the constant pool, we have a real address.

  • Another important feature of run-time constant pools as opposed to Class file constant pools is that they are dynamic.

  • When creating a runtime constant pool for a class or interface, the JVM throws an OutOfMemoryError if the amount of memory required to construct the runtime constant pool exceeds the maximum that can be provided by the method area.

4. Set parameters in the method area

The size of the method area does not have to be fixed, and the JVM can adjust it dynamically based on the needs of the application.

  • Jdk7 and before (permanent generation) :

-xx: PermSize sets the initial space allocation for the permanent generation. The default is 20.75m -xx: MaxPermSize to set the maximum available space for the permanent generation. The default is 64M for 32-bit machines and 82M for 64-bit machine mode

When the number of classes loaded by the JVM exceeds this value, OutOfMemoryError: PermGen Space is raised

  • Jdk8 and later (meta space) :

The metadata area size can be specified using -xx: MetaspaceSize and -xx: MaxMetaspaceSize instead of the previous two parameters.

The default values are platform dependent. On Windows, the value of -xx: MetaspaceSize is 21M, and the value of -xx: MaxMetaspaceSize is -1, indicating that there is no limit.

Unlike the permanent generation, if the size is not specified, the virtual machine uses up all available system memory by default. If the metadata area overflows, the VM also throws OutOfMemoryError: Metaspace.

- XX: MetaspaceSize:Sets the initial meta-space size. For a 64-bit server-side JVM, the default -xx: MetaspaceSize value is 21MB. This is the initial high watermark, and once it is reached, the Full GC will be triggered to unload useless classes (that is, their corresponding classloaders are no longer alive), and the high watermark will reset. The value of the new high water level depends on how much space is freed after GC. If the free space is insufficient, increase this value appropriately until MaxMetaspaceSize is exceeded. If too much space is freed, lower this value appropriately. If the initial high water mark is set too low, the high water mark adjustment described above may occur many times. Multiple calls to the Full GC can be observed from the garbage collector’s logs. To avoid frequent GC, it is recommended to set -xx: MetaspaceSize to a relatively high value.

5. Constant pool

In Java memory allocation, there are three types of constant pools:

5.1. String Constant Pool:

5.1.1: Where is the string constant pool in the Java memory region?
  • In JDK6.0 and earlier, string constant pools were placed inPerm Gen area(that is, method area);
  • In JDK7.0, the string constant pool was moved to the heap. The reason for moving to the heap is probably because the memory space of the method area is too small.
5.1.2: What is a string constant pool?
  • The string Pool functionality implemented in HotSpot VM is oneStringTableClass, which is a Hash table,The default value is 1009; This StringTable has only one copy per HotSpot VM instance, shared by all classes. String constants consist of one character at a time and are placed on StringTable.
  • In JDK6.0, stringTables have a fixed length of 1009, so if you put too many strings into a String Pool, you’ll have hash collisions and the list will be too long. When you call String#intern(), you’ll need to search the list one by one. Resulting in a significant performance decline;
  • In JDK7.0, the length of a StringTable can be specified with an argument:
-XX:StringTableSize=666661
Copy the code

The String#intern() method does this:

  • If the string is not in the Pool, add a record to the Pool and return the reference from the Pool.
  • If it is already in a Pool, the reference in the Pool is returned.

As long as strings in String pools are unreachable to GC Roots, they can be recycled.

If there are too many objects in the Pool, it may cause the YGC to be longer.

5.1.3: What is in the string constant pool?
  • In JDK6.0 and earlier, String pools are String constants;
  • In JDK7.0, because String#intern() has been changed, String pools can also hold references to String objects placed in the heap
  • Note: there is only one string in the string constant pool! Such as:
String s1 = "hello,world!" ; String s2 = "hello,world!" ;Copy the code

After the first line of code is executed, the “Hello,world! , s2 does not apply for new space in the constant pool, but directly returns the existing string memory address to S2.

5.2. Class Constant Pool:

5.2.1 Evolution of constant pools
  • Prior to Java6 and 6, constant pools were stored in the method area (persistent generation).

  • Java7, the constant pool is stored in the heap.

After Java8, the entire permanent generation region was eliminated and replaced with a meta-space. Run-time constant pools and static constant pools are stored in the meta-space, while string constant pools remain in the heap.

5.2.1: Class Constant Pool Introduction
  • Each Java class we write is compiled into a class file; In addition to the class file contains the version, field, method, interface and other description information, there is also an information is the constant pool table, used to store all kinds of Literal and Symbolic References generated by the compiler.
  • Each class file has a class constant pool.
5.2.2: What are literal and symbolic references
  • Literals include: 1. Text strings; 2. Values of the eight basic types; 3.
  • Symbolic references include: 1. Fully qualified names of classes and methods 2. Field names and descriptors 3. The name and descriptor of the method.

5.3. Runtime Constant Pool

  • The runtime constant pool exists in the method area, which is the version of the class constant pool after it has been loaded into memory. The difference is that its literals can be added dynamically (String#intern()), and symbolic references can be resolved to direct references
  • When a JVM executes a class, it must go through loading, wiring, and initialization, and wiring includes three phases: validation, preparation, and parsing. When a class is loaded into memory, the JVM stores the contents of the class constant pool into the runtime constant pool, which is also one for each class. In the parsing phase, symbolic references are replaced with direct references, and the parsing process queries the string constant pool, known as StringTable, to ensure that the strings referenced by the constant pool at run time are consistent with those in the string constant pool.

6.StringTable

Char []

Byte []

String is the main object for storing data in the heap space, and most Latin characters only need to use one byte array to store data. If char is used for data storage, two byte arrays for each character will cause a waste of memory space, so Latin characters are stored in one byte. However, two bytes are still used for Chinese characters, which are distinguished by the identification of character encoding

6.1 Basic String Features

  • When a character variable is reassigned, it is regenerated in the string constant pool

  • The same strings are not stored in the string constant pool

    The string pool is a fixed size hashtable. The default size is 1009 in JDk1.6, 60013 in JDK1.7, and 1009 is the minimum in JDK1.8

    Run the -xx :StringTableSize command to set the size

6.2 String Memory Allocation

Jdk6 and previous, in the methods area

Jdk7 is starting to be placed in the old age of the heap

Because the string constant pool is placed in the method area, the default size of the method area is small and it is not convenient for GC and GC frequency is too low

  • Strings declared directly in double quotes are stored directly in the constant pool
  • Use the String supplied intern() method to load directly into memory

6.3 Concatenating Strings

The result of string concatenation is stored directly in the constant pool. After compile-time optimization, the result string is generated in the string constant pool

As long as there are variables in the concatenated String, a new String() object is required in the heap space, which is the result of the concatenation

String s1="a"; Strinh s2="b"; // The second object String s3=s1+s2; Two objects / / / / StringBuilder s = new StringBuilder () / / s.a ppend (" a ") / / s.a ppend (" b ") / / s.t oString () -- -- -- -- -- - > is approximately equal to the new String (" ab ") // Calls to the toString method will not generate ab in the String constant pool. New String("ab") will generate AB in the String constant pool using StringBuffer before JDk5.0 and Stringbuilder after jdk5.0Copy the code

Adding characters through StringBuilder is much more than concatenating strings

The use of 6.4 intern ()

How do I guarantee that variable S refers to data in the string constant pool

String s = “ABC “;

String s = new String(” ABC “).intern();

String s = new StringBuilder(“abc”).toString().intern();

6.5 New String(“ab”) creates several objects

Two objects, a new String object and a String “AB” object in the constant pool