String pool, runtime constant pool, Class constant pool

Posted May 25, 20207 min read

String pool, runtime constant pool, Class constant pool

First understand the java memory model:

Java virtual machine memory area division diagram:

Area Whether threads are shared Will memory overflow
Program Counter No No
java virtual machine stack no yes
Local Method Stack No Yes
Heap Yes Will
Method Zone Yes Meeting
1 . Program Counter Register

The program counter is to record the position of the current thread executing the program, change the counter to determine the next instruction to be executed, such as:loop, branch, method jump, exception handling, thread recovery are dependent on the program counter to complete.

The multithreading of the java virtual machine is implemented by thread switching and allocating processor execution time. In order to switch the thread to the correct position, each thread requires an independent program counter, so it is thread isolation of.

If the thread is executing a Java method, the program counter of the thread records the instruction address of the byte code of the virtual machine being executed. If the Native method is being executed, the value of the program counter is empty(undefined), This memory area is the only area in the Java Virtual Machine Specification that does not specify any OutOfMemeryError [1](# fn-1).

2 . Java virtual machine stack(vm stack)

The java virtual machine stack is private to threads and has the same life cycle as threads. When the virtual machine executes a Java program, each method creates a stack frame. The stack frame exists in the Java virtual machine stack, and the method is called by pushing the stack out of the stack.

The stack frame is further divided into:local variable table, operand stack, dynamic link, method exit, for example:local variables are stored in the local part of the Java virtual machine stack Variable table. The 8 basic data types are stored in the local variable table. If it is a reference type, the reference address is stored.

*note:

  • When a user requests a web server, each request opens a thread responsible for the user's response calculation(each thread is assigned a virtual machine stack). If the amount of concurrency is large, memory overflow(OutOfMemeryError) may occur. Solution:You can appropriately The size of each virtual machine stack is reduced to reduce the amount of memory used to increase concurrency.
  • But when the stack memory is reduced, it will cause the problem of method call depth. Each method will generate a stack frame. If the method call depth is very deep, it means that there are a large number of stack frames in the stack, which may cause stack memory overflow(StackOverFlowError)
3 . Heap

The heap is an area shared by all threads, which is created when the virtual machine is started. All instances of objects are stored in the heap. The main area of garbage collection is the heap area. In order to improve the performance of garbage collection, the heap area is divided into young generation and old generation(old) . Eden district and two Survivor district(from survivor and to survivor).

  • Eden:The newly created object is placed in the Eden area.
  • From Survivor and To Survivor:Save objects that survive after the new generation gc, Hotspot virtual machine Eden:Survivor = 4:1, that is Eden:From Survivor:To Survivor = 8:1:1
  • Old generation Objects live longer, after multiple new generation garbage collection(default 15 times) objects enter the old generation.
  • When there is too much allocated memory in the heap and most of the objects are in use, it will report a memory overflow(OOM).
4 . Method area

The method area is an area shared by all threads, and is used to store data such as class information, constants, and static variables that have been loaded by the virtual machine. Described by the Java Virtual Machine as a logical part of heap, also known as permanment generation.

Permanent generation will also perform garbage collection, mainly for constant pool collection, type unloading(such as the large number of zero-used Classes generated by reflection).

** Constant pool **Mainly store compiler generated various bytecodes and symbol references, constant pool also has a certain dynamic, which can store constants generated during compilation, during operation ** Constants can also be added to the constant pool, such as the intern() method of String. When the method area is full, a memory overflow exception(OOM) will be reported when space cannot be allocated.

  • There is no method area in Java 8 anymore, replaced by metaspace.
5 . Native Method Stack

The local method stack provides the local method service(Native) used by the virtual machine. The local method stack is private to the thread, and its function is very similar to the virtual machine stack. When the local method is called, the thread stores the local variable table of the local method, the operand stack and other information.

  • The local method stack is a method of calling non-java implementation, for example, Java calls C language to operate certain hardware information.
6 . Direct memory

Direct memory is not part of the virtual machine runtime data area, nor is it the memory area defined in the Java virtual machine memory specification, but this part of memory is also frequently used, which will also cause OutOfMemaryError appear.

In the NIO added in jdk1.4, one method provided by ByteBuffer is allocateDirect(int capacity), which is based on channel and buffer * * The IO ** way, it can use the Native function library to directly allocate off-heap memory, and then operate as a reference to this heap memory through a DirectByteBuffer object stored in the Java heap, so that it is avoided in Java The data is copied back and forth between the heap and the native heap, resulting in significant performance improvements in certain scenarios.

Second, understand the memory allocation of Java objects in the JVM

Take Java8 as an example:

public class Student {

    private String name;
    private static Birthday birthday = new Birthday();

    public Student(String name) {
        this.name = name;
    }

    public static void main(String []args) {
        Student s = new Student("zhangsan");
        int age = 10;
        System.out.println(age);
    }
}

class Birthday {
    private int year = 2010;
    private int month = 10;
    private int day = 1;
}

The Student class executes to the last line of the main method to analyze the allocation of java instance objects in memory.
As shown below:

It can be seen from the figure that the memory allocation of ordinary Java sample objects is mainly in three areas:virtual machine stack, heap, and method area.

To return to the truth

1 . String pool

There are two ways to create string objects in Java:

  • Use literal value to assign value, for example, String name =" chenliang ";
  • Create a new string object using the new keyword method, for example, String name = new String(" chenliang ");

There are differences in performance and memory usage between the two methods.

method one:
public static void main(String []args) {
  String name1 = "chenliang";
  String name2 = "chenliang";
  System.out.println(name1 == name2);
}

When creating a string using the literal method, the JVM first goes back to the string constant pool to find whether the "chenliang" object exists. If it does not exist, the "chenliang" object is created in the string constant pool , And then return the reference address of the object to the string constant name1, then name1 will point to the object "chenliang" in the string constant pool. "The reference address of the object is returned and assigned to the string constant.

The result of this example is:true

Method two:
public static void main(String []args) {
  String name3 = new String("chenliang");
  String name4 = new String("chenliang");
  System.out.print(nam3 == name4);
}

When using the new keyword to create a new string object, the JVM first searches the string pool for the existence of the "chenliang" string object. Instead, create the "chenliang" string object directly in the heap, and then return the reference address of the object in the heap to name3. If the object is not in the string pool, it will be created in the string pool Create a "chenliang" object in the heap and return the reference address of the object in the heap to name3.

The result of this example is:false

This is because every time new is created by the new keyword, it is a new object, so the reference to name3 and name4 refers to two different objects, so the result of using == is false.

\ ###### Use of intern() method:

An initial empty string pool, which is independently maintained by the String class. When the intern() method is called, if the string pool already contains a string equal to this String object( equals(object) method is determined), the string in the pool is returned. Otherwise, add this String string to the string pool and return a reference to the String object. For any two strings s and t, if and only if s.equals(t) is true, s.intren() == t.intern() is true. All literal strings and string assignment constant expressions are operated using the intern() method.

  • Each string constant points to a string instance in the string pool or heap memory.
  • The value of the string object is fixed and cannot be modified once it is created.
  • String constants or strings in constant expressions are all reserved for unique instances in the string constant pool using the String.intern() method.

Note: Shared string objects are maintained in the string pool, and these strings will not be collected by the garbage collector.

2 . Run-time constant pool

Runtime constant pool(Runtime constant pool), it is part of the method area. In addition to the class version, fields, methods, interfaces, and other description information in the Class file, there is also a constant pool, which is used to store various literals and symbol references generated at compile time. Into the constant pool.

Runtime constants are relative to constants. It has an important feature of dynamicity. The Java language does not require constants to be generated at compile time, and new constants can also be generated at runtime. Constants are placed in the runtime constant pool. The constants here include:the packaging type of the basic type and String(using String.intern()).

3 . Class constant pool

Two types of constants are stored in the constant pool:literals and symbol references. Literals are equivalent to the concept of constants in the Java language, such as text strings, constant values declared as final, etc. Symbolic references belong to the concept of compilation principles, including the following constant types:

  • The fully qualified name of the class and interface.
  • Field name and descriptor.
  • Method name and descriptor.

Reference article:

JVM memory model

Memory allocation of JAVA objects in JVM

Java String Pool(Deep Analysis of String Pool)

java virtual machine:runtime constant pool


  1. Refers to an error caused by not being able to apply for enough memory while the program is running. Memory overflow usually occurs after garbage collection in the OLD segment or Perm segment, and there is still no memory space to accommodate new Java objects. The concept of additional memory leak:refers to the dynamic allocation of memory to some temporary objects in the program, but the object will not be recycled by the GC, it always takes up memory. That is, the allocated object reachable but it is useless. [](# fnref-1)