[Jjzhu Java] deep understanding of the memory management mechanism of JVM notes

Source: Internet
Author: User
Tags garbage collection static class throwable xms

Deep understanding of the memory management mechanism of JVM Notes Runtime data Region program counter JVM stack local method stack Java heap method area run frequent pool Direct Memory object access OutOfMemoryError exception Java heap overflow sample JVM stack and local method stack overflow run frequent pool overflow native Direct Memory Overflow

deep understanding of the memory management mechanism of JVM notes run-time data region Program Counter

Each thread has a program counter (PC) that is the line number indicator of the byte code executed by the current thread, and selects the next instruction by changing the value of the program counter. The counters between the threads do not affect each other, and are thread-private memory.
If the thread executes a Java method, the counter records the address of the byte-code instruction being executed, and if the Natvie method is executed, the counter's value is null (undifined).
the memory area in which the program calculator resides is the only memory area in the JVM specification that does not specify Oomerror JVM Stacks

The JVM stack is also an area of memory that is private to each thread, which is allocated as the thread is created, and the thread dies and is recycled. JVM stacks are memory models that describe the execution of Java methods, and each Java method creates a stack frame (stack frame) that is used to store information such as local variables, operation stacks, method exits, and so on in Java methods. Each Java method from the call to execution of the process, is accompanied by the corresponding stack frame in the JVM stack into the stack and into the stack.
In the JVM specification, there are two exception conditions in this area:
-Stackoverflowerror: The stack depth requested by the thread exceeds the stack depth allowed by the JVM stack
-OutOfMemoryError: If the JVM stack is dynamically extensible, throw the exception local method Stack when it is not possible to request enough memory

The local stack (Native method stack) is a memory model that describes the local methods used by the virtual machines, similar to the JVM stack, and throws Stackoverflowerror and OutOfMemoryError java heaps

The Java heap is the largest area of memory managed by a Java virtual machine, and what we call garbage collection is the memory of the zone being reclaimed, so it is also called the GC heap. The Java heap is the area of memory that is common to all threads, and the objects and arrays in the program are stored in the area.
From the point of view of memory recycling, because the collector is now used by the collection algorithm, so the Java heap can be further subdivided into: the new generation and the old era, in the Cenozoic, but also can be divided into Eden, from the survivor, to survivor and other space. From the point of view of memory allocation, the Java heap may be divided into multiple thread-private allocation buffers.
The Java heap can be a physically discontinuous but logically contiguous memory space that can be set to the Java heap size by specifying VM parameters such as-XMX (max),-xms (min),-xmn (Cenozoic). If a new object requests memory space But the Java heap does not have enough memory allocations, it will report oomerror. Method Area

The method region is also a shared memory area for each thread, which is used to store data that is loaded by the virtual machine, constants, static constants, compiled code, and so on, with a separate name non-heap (not a heap), which distinguishes it from the Java heap. On the hotspot virtual machine, it is also called "permanent generation" (permanent Generation), which is inherently not equivalent (Hotspot extends GC collection to the zone).
To make GC for this area, it is primarily to reclaim the constant pool and unload the type. This area also throws Oomerror exceptions when memory is full. run a constant-amount pool

The runtime (Runtime Constant Pool) is part of the method area, in addition to the description of the version, field, method, interface, etc. of the class file, and also the constant pool table, which is used to store the GE constants and symbolic primers generated during compilation. This part of the content is stored in a run-time pool after the class is loaded (how class loading is mentioned in the later chapters). The runtime is dynamic, the Java language does not only produce constants during compilation, but it may also put new constants into the Run-time pool during run time, such as when the developer uses the String.intern () method, and then the exception test is to use this method to cause the constant pool to throw oomerror. Direct Memory

Direct memory is not part of a virtual run-time data region, nor is it a memory area defined in the JVM specification, but it is also used frequently by Memory. Since JDK1.4, an I/O method based on channel (Channel) and buffer is introduced, which can directly allocate the heap memory using the native function library and manipulate the block memory through the Directbytebuffer object in the Java heap. Eliminates data replication Between the Java heap and the native heap, improving performance.
Native Direct memory is not limited by the Java heap size, but is limited by the total native memory size and the addressing space of the processor. Oomerror exceptions are also thrown when dynamically expanding. Object Access OutOfMemoryError Exception

This paper describes the virtual Run-time data region, and now verifies the occurrence of oom anomaly by an instance, and can further understand the storage contents of each memory region of the JVM and the occurrence of abnormal situation.
The Java version of the test is:

Java Version "1.7.0_80"
Java (TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot (TM) 64-bit Server VM (build 24.80-b11, Mixed mode) Java heap Overflow sample

As mentioned earlier, object instances are stored in the Java heap, so you can constantly create objects and make the Java heap overflow without the object being GC
Write the following code list:

/** 
* @ClassName: Heapoom 
* @Description: Java heap memory overflow anomaly Test
* @author Kang Jiajun (jjzhu_ncu@163.com)
* @date October 18, 2016 PM 8:30:13 
* VM Args:-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror * * Public
class Heapoom { C7/>static class oomobject{ 
    } public

    static void Main (string[] args) {
        list<oomobject> List = new
  arraylist<oomobject> ();
        while (true) {
            list.add (new Oomobject ());}}}

and configure the Run-time VM parameters:

here the-XX:USEPARNEWGC is specified with the Parnew collector, the default is
Parameter explanation:-xms:20m:java heap Minimum 20M
-xmx:20m:java heap Max 20M (avoid dynamic expansion)
-xx:+heapdumponoutofmemoryerror: Opens this option to allow the virtual machine to dump the current memory heap dump snapshot when the OutOfMemoryError is thrown
After running, you will have the following output:

Java.lang.OutOfMemoryError:Java Heap Space
dumping heap to java_pid3576.hprof ...
Heap dump file created [34233497 bytes in 0.301 secs]
Exception in thread "main" Java.lang.OutOfMemoryError:Java Heap Space in
    java.util.Arrays.copyOf (arrays.java:2760) at
    java.util.Arrays.copyOf (arrays.java:2734)
    at Java.util.ArrayList.ensureCapacity (arraylist.java:167) at
    java.util.ArrayList.add (arraylist.java:351)
    At Study.hard.jjzhu.HeapOOM.main (heapoom.java:20)
JVM Stack and local method stack Overflow

As mentioned before, the hotspot virtual machine does not differentiate between the JVM and the local method stack. The size of the stack can be specified in the Hotspot virtual machine by setting the-XSS parameter.
Write the following test code:

/** 
 * @ClassName: Javavmstacksof 
 * @Description: Virtual machine stack and local method stack oom test 
 * @author Kang Jiajun (jjzhu_ncu@163.com)
 * Date October 18, 2016 PM 9:09:21 
 *  VM Args:-xss128k * * Public
class Javavmstacksof {
    private int Stacklength = 1;
    public void Stackleak () {
        stacklength + +;
        Recursive call
        stackleak ();

    }

    public static void Main (string[] args) throws Throwable {
        javavmstacksof oom = new Javavmstacksof ();
        try{
            oom.stackleak ();
        } catch (Throwable e) {
            System.out.println ("Stack deep:" + oom.stacklength);
            throw e;
        }}}

The stackoverflowerror exception is reported when it is run:

Stack deep:1007
Exception in thread ' main ' Java.lang.StackOverflowError
    at Study.hard.jjzhu.memory.JavaVMStackSOF.stackLeak (javavmstacksof.java:13) at
    Study.hard.jjzhu.memory.JavaVMStackSOF.stackLeak (javavmstacksof.java:15) at
    Study.hard.jjzhu.memory.JavaVMStackSOF.stackLeak (javavmstacksof.java:15) at
    Study.hard.jjzhu.memory.JavaVMStackSOF.stackLeak (javavmstacksof.java:15)
run a constant-amount pool overflow

The String.intern () method can be added to the running constant pool, so to achieve a runtime overflow, execute a local method intern () as the constant addition of strings in the pool can be-xx:permsize-xx: MaxPermSize limits the method area size.

/** 
 * @ClassName: Runtimeconstantpooloom 
 * @Description: Method area and run frequent pool overflow
 * @author Kang Jiajun (jjzhu_ncu@163.com)
 * @date October 18, 2016 PM 9:18:07 
 * VM Args:-xx:permsize=10m-xx:maxpermsize=10m * * Public
Class runtimeconstantpooloom {public
    static void Main (string[] args) {
        list<string> List = new arraylist< String> ();
        int i = 0;
        while (true) { 
             /* String.intern () is a native method that if the string constant pool contains a string equivalent to this string
             * object, Returns a String object of this string in the constant pool, otherwise the string contained by this string object is added to the constant pool,
             * and the reference to this string object is returned
            /List.add (string.valueof + +). Intern ())
        ;
}} > Run Result:
Exception in thread "main" java.lang.OutOfMemoryError:PermGen spaces at
    Java.lang.String.intern ( Native method) at
    Study.hard.jjzhu.memory.RuntimeConstantPoolOOM.main (runtimeconstantpooloom.java:23)
Native Direct Memory overflow

Native Direct memory can specify the memory size by-xx:maxdirectmemorysize, and if not specified, the default is the same as the maximum Java heap.

/** 
* @ClassName: Directmemoryoom 
* @Description:  native Direct Memory Overflow
* @author Kang Jiajun (jjzhu_ncu@163.com)
* Date October 18, 2016 PM 9:41:40 
* VM Args:-xmx20m-xx:maxdirectmemorysize=20m * * Public
class Directmemoryoom {
    private static final int _1MB = 1024 * 1024;
    public static void Main (string[] args) throws IllegalArgumentException, illegalaccessexception {
        Field Unsafefield = Unsafe.class.getDeclaredFields () [0];
        Unsafefield.setaccessible (true);
        Unsafe Unsafe = (Unsafe) unsafefield.get (null);
        while (true) {
            unsafe.allocatememory (_1MB);
        }
}} Exception in thread ' main ' java.lang.OutOfMemoryError at
    sun.misc.Unsafe.allocateMemory (Native method)
    at Study.hard.jjzhu.memory.DirectMemoryOOM.main (directmemoryoom.java:21)

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.