Java memory management (heap and stack) and garbage collection algorithm


About a .Jvm virtual machine memory

1.1 Java runtime memory zone

Memory composition shown below Java runtime:
Here Insert Picture Description

1.2 thread private follows:

  • 程序计数器

    Byte code executed by the current thread indicator line number

  • Java虚拟机栈

    Java memory model execution method, when each method is executed creates a stack frame, the local variable table storage, operation information stack, dynamic linking, method exports.

    • Each thread has its own independent stack space
    • Thread stack memory only basic types and object address (focus)
    • The method of local variables in the thread space (focus)
  • 本地方法栈

    Native method of service. In the HotSpot virtual machine and the Java virtual machine stacks combined.

1.3 threads share is as follows:

  • Java堆

    Storing object instance, almost all of the object instances and their attribute allocate memory here. (Focus)

  • 方法区

    Class information storage has been loaded virtual machine, constants, static variable, the JIT compiled code and other data.

  • 运行时常量池

    Region part of the method. For storing various literal and compile generated reference symbols.

Here Insert Picture Description

  • Direct Memory

    NIO, Native functions directly allocated off heap memory. DirectBuffer references will use this part of the memory.

Two .Java stack and heap

2.1 stack concepts and features

Java the memory is divided into two: One is the stack memory, one is the heap memory.

In 栈内存the storage variable type base and local variables of methods and reference variable object .

In 堆内存used to store objects and arrays created by the new new .

Here Insert Picture Description
在栈内存中保存的是堆内存空间的访问地址,或者说栈中的变量指向堆内存中的变量(Java中的指针)

Detailed explanation:
in the heap produce an array or object, the definition of a special variable in the stack, the stack so that the value of this variable is equal to the first address of the array or object in the heap memory, stack variables into this an array or object reference variables.

Reference variable is equivalent to a name from the array or object, since you can access the heap array or object reference variables using the stack in the program.

When defining a variable block of code, Java stack is allocated in variable memory space, when exceeding the scope of variables, Java automatically freed memory space allocated for the variable, the memory space can be immediately for other purposes.

In the memory allocated on the heap, managed by automatic garbage collector Java virtual machine.


2.2 stack and heap similarities and differences

Java stack and heap are used to store data in place of Ram. Unlike C ++, Java automatically manage the stack and heap, the programmer can not directly set the stack or heap.

A Java heap is the runtime data area, the class (object space dispense these objects by establishing new, newarray, anewarray multianewarray and other instructions, program code, they do not need to explicitly release. Heap garbage collection is responsible for the of,

The advantage is that heap memory size can be allocated dynamically, survival do not have to tell the compiler in advance, because it is at run-time dynamic allocation of memory, Java's garbage collector automatically taken away these data is no longer in use. But the disadvantage is due to the slower dynamic allocation of memory access speed at runtime.

Stack advantage is that the access speed is faster than the reactor, after register, stack data can be shared. But the disadvantage is that there is data in the stack size and survival must be determined, lack of flexibility. The main stack store some basic types of variables (, int, short, long, byte, float, double, boolean, char), and the object handle.

For example 2.3

Stack has a very important particularity is that there is data in the stack can be shared. Suppose we also define:

int a = 3;
int b = 3
  1. The compiler first deal with int a = 3; first it will create a variable as a reference in the stack, and then find out whether there is value 3 stack, if not found, it will come in store 3, then a 3 point.
  2. Followed by treatment int b = 3; b After creating the reference variable, as it has the value 3 in the stack, directly to put b 3.
  3. Thus, there have been cases a and b simultaneously point to 3.
  4. At this time, if we make a = 4; then the compiler will search again if there are 4 value stack, and if not, then the 4 stored in, and make a point to 4; If you already have, then this address directly to a point .
  5. Thus a change does not affect the value of the value b.

This sharing is to be noted with reference to two simultaneous data objects to an object such sharing is different, because such a situation does not affect the modification B, it is done by the compiler, it facilitates save space . And a object reference variable to modify the internal state of this object will affect another object reference variables .

String is a special wrapper class data. It can be created using only two forms, on the stack or the constant pool (Method region):

String str = new String("abc");
String str = "abc";
  • The first is to use new () to create a new object, this syntax is 堆中to create objects, and str point to it, then go to the string constant pool to see if there is an object with the same content, and if so, Object string object string constant pool will be out of the new link, if not, then create a string object that contains the contents of the string constant pool, in-memory objects with string and heap constant pool of new objects out link.
    This is one input string, lifelong memory return mechanism, benefit comparison string.
  • The second is to create a stack object reference variable str String class, and then find 常量池中there is no storage of "abc", if not, then "abc" stored into the constant pool, and to make str point "abc", if We have "abc" is the direct cause of str point "abc".
  • Pay attention: We use such as String str = "abc"; the format defined class, you may not create a new object str String class, could only point to an object that has been previously created, use a new () can be guaranteed every time a new object.
  String str1 = "aaa";
 //解析:str1指向方法区;

  String str2 = "bbb";
 //解析: str2 指向方法区

  String str3 = "aaabbb";
  //解析:str3指向方法区

  String str4 = str1 + str2;
  //解析:此行代码执行的底层执行过程是 首先使用StringBuffer的append方法将"str1"和"str2"拼接在一块,然后调用toString方法new出“str4”;所以此时的str4是创建在堆区的

  String str5 = "aaa" + "bbb";
  //解析:该行代码重点说明一下,jvm对其有优化处理,也就是在编译阶段就会将这两个字符串常量进行拼接,也就是"aaabbb";所以他是在方法区中的;’

  System.out.println(str3 == str4); // false or true
 //解析:很明显 为false, 一个指向堆 一个指向方法区

  System.out.println(str3 == str4.intern()); // true or false
 //解析:jdk1.6中str4.intern会把“aaabbb”放在方法区,1.7后在堆区,所以在1.6中会是true 但是在1.7中是false

  System.out.println(str3 == str5);// true or false
  //解析:都指向字符串常量区,字符串长常量区在方法区,相同的字符串只存在一份,其实这个地方在扩展一下,
  //因为方法区的字符串常量是共享的,在两个线程同时共享这个字符串时,如果一个线程改变他会是怎么样的呢,
  //其实这种场景下是线程安全的,jvm会将改变后的字符串常量在
  // 字符串常量池中重新创建一个处理,可以保证线程安全

Another note:

  • (1) The memory has a base type package java class constant pool. These classes include Byte, Short, Integer, Long, Character, Boolean. Note that, Float and Double these two categories did not correspond to the constant pool.

  • . (2) Integer object wrapper classes is the presence of five kinds of the above defined range; range exists partitioned heap constant pool outside, in the range of -128 to 127.

  • (3) that there is present in Zhou Zhiming virtual machine saying: packaging the "==" symbol does not automatically run without unpacking encountered arithmetic operations, and their equals () method does not handle data relationship type, i.e. popular talk "= =" on both sides, if there is an arithmetic operation, then automatically unpacking and data type conversion processing, comparing the numerical values ​​can vary.

  • (4) .Long equals method first determines whether the Long.

  • (5) whether it is Integer or Long, they are the equals method to compare values.

    Integer a = 1;
    Integer b = 2;
    Integer c = 3;
    Integer d = 3;
    Integer e = 321;
    Integer f = 321;
    Long g = 3L;

    System.out.println(c == d); //  true
    //解析:由于常量池的作用,c与d指向的是同一个对象(注意此时的==比较的是对象,也就是地址,而不是数值)。
    
    System.out.Println(e == f); // false
    //由于321超过了127,因此常量池失去了作用,所以e和f数值虽然相同,但不是同一个对象。
    
    System.out.println(c == (a + b)); // true
    //此时==两边有算术运算,会进行拆箱,因此此时比较的是数值,而并非对象。
    
    System.out.println(c.equals(a+b)); // true
    //c与a+b的数值相等。
    
    System.out.println(g == (a + b)); // true。
    //由于==两边有算术运算,所以比较的是数值。
    
    System.out.println(g.equals(a + b)); // false
    //Long类型的equal在比较是时候,会先判断a+b是否为Long类型,显然a+b不是.

III. Garbage collection algorithm

3.1 GC mechanism

Java GC (Garbage Collection, garbage collection, garbage collection) mechanism, is one of the main differences between Java and C ++ / C as a Java developer, generally do not need to write special garbage collection and garbage cleanup code. This is because the Java virtual machine, there is automatic memory management and garbage cleaning mechanism. The mechanism of the JVM (Java Virtual Machine) to mark the memory, memory and determine which need to be recovered, according to some recovery strategy, automatic recovery of memory, never stops (Nerver Stop) to ensure the JVM memory space, to prevent memory leaks and overflow.

GC recovery is useless object, and after the object is created in the heap jvm, jvm heap so first look

JVM stack (generational method) is divided into

  • (1) a new domain: storing all of the objects into the new born (using the "Stop - Copy" algorithm clean)
      the new generation memory is divided into two parts:
       the first part region Eden, larger space;
       comparing a second portion Survivor areas, space small, and is divided into two equal portions.

  • (2) the old domain: target new domain, through the GC after a certain number of cycles, it is moved into the old domain (algorithm is labeled - Collation Algorithm )

  • (3) permanent field (Method Area): storage class and method object from the point of view configuration, the field is independent, not included in the JVM stack. The default is 4M.

The method of recovery zone (permanent field) in two ways:

  • Constants pool
  • Useless class information

Constant recovery is very simple, no references can be recycled.
For recovery unnecessary class, we must ensure three points:

  • All instances of the class have been recovered
  • ClassLoader loaded class has been recovered
  • Class object is not referenced object class (i.e., is not reflected by the local reference class)

Recycling must not permanently domain, can be set by parameters are based on the recovery.

3.2 GC process

When eden full, triggering Young GC , GC Young to do two things:

  • A, Object useless part removed;
  • Second, the old also made reference to the object to survior inside, wait for the next several GC later, survivor again into old inside.

When the old full, triggering Full GC . full GC-consuming memory, the old, young inside most of the garbage out. This time user threads will be block.

3.3 GC algorithm

(. 1) Mark-Sweep mark - sweep algorithm

Through all GC Root, respectively, up to mark objects and objects unreachable, then unreachable objects recovered.

优点是:内存消耗较复制法小
缺点是:效率低、回收得到的空间不连续

The establishment of a number of root object (GC Root), each object is a child node, when an object can not find the root, they believe the object is unreachable.

Here Insert Picture Description

Not a path from the root to the Object4 and Object5, indicating that two objects to the root is not reachable, it can be recovered

Supplementary: java can be used as an object GC Roots include:

  • java virtual machine stack referenced objects
  • The method of the object in a static variable references
  • The method of constant reference object region
  • Native method stacks referenced objects

(2) Copying Collector replication algorithm

The memory is divided into two, each with only one. When this piece of memory is full, the copy will also live objects to another piece, and in strict accordance with the arrangement of the memory address, and then the piece of used memory uniform recycling.

Advantages: the ability to obtain a continuous memory space high efficiency
disadvantages are: waste of half of the memory

(3) Mark-Sweep-Compact mark - Collation Algorithm
for the removal of objects, will produce some memory fragmentation, this time we need to compress these memory consolidation. Comprising: relocate (the inventory object is moved together thereby releasing successive available memory), remap (collect all object references to the new address of the object). Efficiency and the number of live objects are linearly related.

3.4 Common minor problems 1: Java program whether there will be a memory leak

Answer: A memory leak occurs.

In general there are two cases memory leaks. First, the memory allocated on the heap, in the absence of its release out, it will be able to access all the way this memory are deleted; the other case is clearly the object in memory when no longer needed, but also still retain this memory and its access method (reference). The first case, Java has been due to the introduction of garbage collection mechanism, it has been solved. So, Java memory leaks in, mainly refers to the second case.

Here is an example of a simple memory leak. In this example, we apply for circulating Object object, and the object of the application into a List, if we only release the reference itself, the List still refer to the object, so the object of the GC is non-recyclable. Code as follows:

    List list=new ArrayList(10);
    for (int i=1;i<100; i++)
    {
        Object o=new Object();
        list.add(o);
        o=null;    
    }

At this point, all the Object object have not been released because the variable list to refer to them.

3.5 Common minor problems 2: JVM how to manage memory, divided into several parts? They were of any use? Speak memory to achieve the principles of the following codes:

Foo foo = new Foo();
foo.f();

Answers

JVM memory divided into three regions "stack", "stack" and "area method", each for a different data storage.
  Heap memory used to store objects created using the new keyword; stack memory for storing all local variables declared in the program is running method, the basic types and object addresses; the method area for information storage classes, Java programs run when the information is first loaded bytecode class files by the class loader, which was charged after a lapse of analytical method area. The various categories of information (including the methods) are stored in the method area.

Code memory to achieve the above principle is: (focus)
  1.Foo class first loaded into the JVM 方法区, including the class information, including a method and structure and the like.
  2. In 栈内存reference variable foo allocated.
  3. In 堆内存allocating memory in accordance with Foo instance variable type information; then, the stack reference point foo foo object heap address of the first memory.
  4. The method of using the call reference foo, the type of call Foo f foo reference method.


Article refer to the following blog:
https://blog.csdn.net/u010429424/article/details/77333311#commentBox
https://blog.csdn.net/wulianghuan/article/details/8599181
https://www.imooc.com / Article This article was / 68981
https://www.cnblogs.com/lyf906522290/p/8350756.html

Guess you like

Origin blog.csdn.net/qunqunstyle99/article/details/94005430