Java memory area and simulated memory area exception

Source: Internet
Author: User

I drew a mind map of the memory area of Java and the main functions of each area.

simulating Java heap overflow

The Java heap is used to store object instances. It is only necessary to constantly create objects and ensure that the GC roots between objects has an accessible path to avoid being purged by the recycle mechanism. will be able to simulate a Java heap overflow.

 PackageHXL.INSIST.JVM;ImportJava.util.ArrayList;ImportJava.util.List;/** * The following is the JVM Args: * Minimum value of the-xms20m heap-xmx20m heap (set to the same to prevent the heap from actively expanding) *-xx:+heapdumponoutofmemoryerror when a memory overflow exception occurs on the virtual machine, D UMP out the current heap dump snapshot *-xx:heapdumppath=e:\eclipseworkspace\understandingthejvm\hprof set the path to the generated heap dump snapshot * @author HANXL * */ Public  class heapoutofmemory {    StaticClass Stuffobject {}Staticlist<stuffobject> list =NewArraylist<stuffobject> (); Public Static void Main(string[] args) {Thread thread =NewThread (NewRunnable () { Public void Run() {createobj ();         }        });    Thread.Start (); }Private Static void Createobj() { while(true) {List.add (NewStuffobject ()); }    }}

Analyze the heap dump with Memoryanalyzer as usual:

The shortest path from the root element to the memory-consuming aggregation point can see the entire chain of references very clearly.

In the above diagram, we can clearly see that this object collection holds a large number of references to internal class Stuffobject objects, which is the memory leak caused by it.

simulating Java Virtual machine stack Overflow

With respect to the virtual machine stack, two exceptions are regulated in the Java Virtual machine:

    1. Assuming that the stack depth requested by the thread is greater than the maximum depth agreed by the virtual machine, the Stackoverflowerror exception is thrown.
    2. If you cannot request enough memory space when the virtual machine is expanding the stack, throw a OutOfMemoryError exception.

Simulate the first case:

package hxl.insist.jvm;/** * 以下是JVM Args: * -Xss128k 设置栈容量大小 * @author hanxl */publicclass JavaVMStackSOF {    publicvoidstackLeak() {        stackLeak();    }    publicstaticvoidmainthrows Throwable {        new JavaVMStackSOF().stackLeak();    }}

Simulate a different situation:

 PackageHXL.INSIST.JVM;/** * Below is the JVM Args: *-xss2m Set Stack capacity * @author HANXL */ Public  class javavmstackoom {     Public Static void Main(string[] args) {NewJavavmstackoom (). Threadinvokemethod (); } Public void Threadinvokemethod() { while(true) {Thread thread =NewThread (NewRunnable () {@Override                 Public void Run() {infiniteloop ();            }            });        Thread.Start (); }    }Private void Infiniteloop() { while(true)              ; }}
Why do the two situations differ in how they are implemented?

The Java Virtual machine stack is thread-private, with the same lifetime as the thread. We make a virtual machine stack than a box,-XSS is the size of the box, and a thread can only correspond to a box. Each Java method, when run, creates a stack frame in the box to store some information such as a local variable table.

So in order to create the exception in the first case, we set the size of the box smaller, using recursion to constantly invoke the method, thus bursting the box. In order to create an exception in another case, we should set the size of the box a little larger, creating more boxes so that it cannot request enough memory space.

Just to understand the memory area of the mind map above, it is also very easy to simulate other memory area anomalies.

Java memory area and simulated memory area exception

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.