Explain the usage of stack, heap and method area in memory.

Usually we define a variable of a basic data type, a reference to an object, and the on-site storage of function calls all use the stack space in the JVM; while the objects created by the new keyword and the constructor are placed in the heap space, the heap is The main area managed by the garbage collector. Since current garbage collectors adopt generational collection algorithms, the heap space can also be subdivided into young and old generations. More specifically, it can be divided into Eden and Survivor (which can be divided into From Survivor and To Survivor), Tenured; method area and heap are memory areas shared by each thread, used to store data such as class information, constants, static variables, and code compiled by the JIT compiler that have been loaded by the JVM; Literals such as 100, "hello" and constants written directly are placed in the constant pool, which is part of the method area. The stack space is the fastest to operate but the stack is small. Usually a large number of objects are placed in the heap space. The size of the stack and the heap can be adjusted by the startup parameters of the JVM. If the stack space is used up, a StackOverflowError will be triggered. Insufficient space in the constant pool will cause OutOfMemoryError.

String str = new String("hello");

In the above statement, the variable str is placed on the stack, the string object created with new is placed on the heap, and the literal "hello" is placed in the method area.

Supplement 1: In the newer version of Java (starting from a certain update of Java 6), due to the development of the JIT compiler and the gradual maturity of "escape analysis" technology, optimization techniques such as stack allocation and scalar substitution make the object must be allocated in This matter has become less absolute.
Supplement 2 : The runtime constant pool is equivalent to the class file constant pool which is dynamic. The Java language does not require constants to be generated only during compilation, and new constants can also be placed in the pool during runtime. The intern() method of the String class That's it.

Take a look at the execution result of the following code and compare whether the previous and future results of Java 7 are consistent.

String s1 = new StringBuilder("go")
    .append("od").toString();
System.out.println(s1.intern() == s1);
String s2 = new StringBuilder("ja")
    .append("va").toString();
System.out.println(s2.intern() == s2);

Java training

Guess you like

Origin blog.csdn.net/msjhw_com/article/details/109237099