Java memory model and GC algorithm

Source: Internet
Author: User
Tags exception handling java se

1.java memory Model 1. JVM Memory model

The JVM memory model, for example, needs to be declared, which is what is specified in the Java Virtual Machine specification (Java SE 7), and the actual area is implemented by each JVM itself, so it may be slightly different. The following is a brief description of each region.

1.1 Program Counters

Program counter is a common part of many programming languages, the role is to mark the next need to execute the location of the instruction, branch, loop, jump, exception handling, thread recovery and other basic functions are dependent on the program counter.

For Java multithreaded programs, different threads are run by taking the time slice of the CPU in turn, which conforms to the basic concept of the principle of computer composition, so the different threads need to get running continuously, suspend waiting to run, so the counters between each thread do not affect each other, independent storage. These data areas belong to thread-private memory.

1.2 Java Virtual Machine stack

VM Virtual machine stacks are also thread-private, with the same life cycle as threads. The virtual machine stack describes the memory model that the Java method executes: Each method creates a stack frame to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on. Each method call until the completion of the process, corresponding to a stack frame in the virtual machine stack into the stack of the process.

Some people divide the Java memory area into two parts: Stack and heap, in which the stack is labeled as the current virtual machine stack, or the local variable table corresponding to the virtual machine stack. The reason that this division is relatively rough angle is different, this division is concerned about the new application of memory space, and we are talking about the JVM as a whole memory division, because of different angles, so the division of different methods, there is no right and wrong.

The local variable table holds various basic types, object references, and returnaddress that are known during compilation. where 64 bits long and double occupy 2 local variable space (slot), other types Occupy 1. This also illustrates the non-atomic nature of long and double in terms of storage. The memory required for the local variable table is allocated during compilation, and when entering a method, the method allocates much of the local variable space in the stack frame is fully deterministic and does not change the local variable table size while the method is running.

Due to the stack frame in and out of the stack, it is obvious that the space allocation problem. If the thread requests a stack depth greater than the virtual machine allows, the Stackoverflowerror exception is thrown, and if the virtual machine stack can be extended, the extension cannot request enough memory to be thrown outofmemoryerror. Obviously, most of this happens due to cyclic invocation and recursion.

1.3 Local Method Stack

The local method stack is very similar to the virtual machine stack, but the local method serves the native method. Some virtual machines, such as Sun hotspot virtual machines, merge the local method stack directly with the virtual machine stack. As with the virtual machine stack, the local method stack throws Stactoverflowerror and OutOfMemoryError exceptions.

At this point, the thread private data area ends and the thread-sharing data area begins below.

1.4 Java Heap

The Java heap is the largest piece of memory managed by a virtual machine, created at the time of virtual machine startup, the only purpose of this block of memory is to hold object instances, and almost all object instances allocate memory on the pair. The description in the JVM specification is that all object instances and data are allocated on the heap. However, with the development of JIT compiler and the gradual maturation of the escape analysis technology, the stack allocation (the object only exists in a method, will not escape, so the method will be destroyed after the stack, the object can be allocated on the stack, easy to destroy), scalar substitution (The new object owns the properties can be replaced by existing objects together, There is no need to actually generate this object) optimization techniques have brought some changes, and not all objects are currently allocated on the heap.

The OutOfMemoryError exception will be thrown when there is no memory complete instance allocation on the Java heap, and the heap size cannot be extended. The Java heap is the primary area of garbage collector management.

1.5 Method Area

The method area, like the Java heap, is a thread-shared data area that stores the class information, constants, static variables, and immediately compiled code that are loaded by the virtual machine. The JVM specification separates the method from the heap, but the hotspot implements the method area as a permanent generation (Permanent Generation). This makes it easy to extend the GC-generational approach to the method area, where the hotspot's garbage collector can manage the method area just as the Java heap is managed. However, this direction has been gradually replaced by the hotspot, in the version of JDK1.7, has been stored in the method area of the string constant area of the move out.

At this point, the memory model declared by the JVM specification has been parsed, and some of the frequently mentioned memory-related areas are analyzed below.

1.6 Running a constant-rate pool

Running a constant pool is part of the method area. class file In addition to the class version, fields, methods, interfaces, and other information, there is a constant pool (Constant Poll Table) used to hold the compilation of the various literal and symbolic references generated, which will be loaded in the class load in the run-time method area of the runtime constant pool storage.

Where the string constant pool is part of the run-time pool, but in the hotspot virtual machine, JDK1.7 moves the string constant pool to the Java heap, which can be easily seen through the following experiment.

 import   java.util.ArrayList;  import   java.util.List;  public  class   runtimecontantpooloom { public  static  void   main (String        [] args) {List List  = new   ArrayList ();         int  i = 0;  while  (true         ) {List.add (string.valueof (i  ++

In jdk1.6, the string constant area is in Perm space, so you can set the Perm spacce smaller, xx:maxpermsize=10m can quickly throw an exception: Java.lang.OutOfMemoryError:Perm Space.

Above jdk1.7, the string constant area has been moved to the Java heap, set-xms:64m-xmx:64m, and can soon throw an exception java.lang.OutOfMemoryError:java.heap.space.

1.7 Direct Memory

Direct memory is not part of the data area of the JVM runtime, nor is it an area of memory defined in the Java Virtual Machine specification. The NIO (New Input/output) class was introduced in JDK1.4, which introduced a channel-based (Chanel)-to-buffers (buffer) I/O approach that he could use to directly allocate out-of-heap memory using the native library. It then operates as a reference to this memory through a Directbytebuffer object that is stored in Java. This can significantly improve performance in some scenarios because it avoids copying data back and forth between Java pairs and native pairs.

2.GC Algorithm 2.1 mark-Clear algorithm

The most basic garbage collection algorithm is the "mark-clear" (Mark Sweep) algorithm, which, like the name, is divided into 2 stages: 1. The object to be reclaimed at the mark, 2. Reclaims the Tagged object. There are two types of tagging algorithms: 1. Reference counting algorithm (Reference counting) 2. Accessibility analysis Algorithm (reachability analyses). Because the reference technology algorithm cannot solve the problem of circular reference, the tagging algorithm used here is the accessibility analysis algorithm.

, a large amount of non-contiguous memory occurs after the tag cleanup algorithm has been performed. When the Java heap needs to allocate a contiguous amount of memory to a new object, it is found that while the memory cleanup is a lot of idle, it still needs to be cleaned up to meet the "continuous space" requirement. Therefore, this method is relatively basic, the efficiency is also relatively low.

2.2 Copy algorithm

To solve the problem of efficiency and memory fragmentation, the replication (Copying) algorithm appears, dividing the memory into two equal sizes, one at a time, when this piece is used up, the surviving object is copied to another memory area, and the current memory space is cleaned out once. In this way, the entire half of the area is recycled, allocated sequentially from the top of the memory, this implementation is simple, efficient operation. However, this algorithm reduces the original memory space to the actual half, the cost is relatively high.

It can be seen that the memory after finishing is very regular, but wasted the general memory cost is too high. However, this is a very important collection algorithm, because today's commercial virtual machines are using this algorithm to reclaim the new generation. IBM's research has shown that object 98% in the Cenozoic is "dying from the dead", so there is no need to divide the memory by a 1:1 ratio. The hotspot virtual machine divides the Java heap into younger generations (young Generation), the older generation (tenured Generation), where the young generation is divided into a piece of Eden and two pieces of survivor.

All new objects are placed in the younger generation, and the GC algorithm used by the younger generation is the copy algorithm. The ratio of Eden to Survivor is 8:2, where Eden consists of 1 chunks and survivor consists of 2 small pieces. Each use of memory is 1eden+1survivor, which is 90% of memory. Because the object life cycle of the young generation tends to be short, the original Eden and survivor will be emptied when a GC is required to copy the current 90% surviving objects into another survivor. But there is a problem, and we cannot guarantee that every young generation GC will survive no more than 10%. So when the living object is above 10%, this part of the object will be guaranteed by tenured, i.e. objects that cannot be copied into the survivor will move to the old age.

2.3 Labeling-Sorting algorithm

The replication algorithm becomes very inefficient in extreme cases (many of the surviving objects) and requires additional space for allocation guarantees. So in the old age this situation is generally not suitable.

So there's the tagging-sorting (mark-compact) algorithm. As with the markup cleanup algorithm, the first is to tag the object, but the second step is to move the inventory object to the memory section, sorting out a larger contiguous memory space.

3. Summary
    1. The Java Virtual Machine specification specifies the allocation of memory, where the program counter, the local method stack, the virtual machine stack belong to the thread private data area, and the Java heap and the method area belong to the thread sharing data.
    2. The JDK moves the string constant area from 1.7 to the Java heap, starting with the method area (permanent generation).
    3. Java starts by allowing direct manipulation of the system's direct memory from NIO, which is highly efficient in some scenarios because it avoids replicating data back and forth in the Java heap and the native heap.
    4. The Java heap is divided into younger generations with older generations, of which the young generation is divided into 1 Eden and 2 Survior, while only 1 Eden and 1 Survior are in use, and the younger generation objects are often short-lived, so the replication algorithm is used for garbage collection.
    5. Older generations because object lifetimes are long and there is no data area to vouch for, garbage collection is often done using tag-clear and tag-grooming algorithms.

Java memory model and GC algorithm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.