In-depth understanding of Java Virtual Machine learning note 2--java Memory overflow instance

Source: Internet
Author: User

Demonstrate the memory overflow scenario for each part of a Java virtual machine with a simple, small example program:

(1). java Heap Overflow:

The Java heap is used to store instance objects, as long as the objects are constantly created, and the GC roots is guaranteed to have a reference between the objects, preventing the garbage collector from reclaiming instance objects, which produces an OutOfMemoryError exception when the number of objects reaches the maximum heap capacity.

To quickly and easily generate heap overflows, use the following Java Virtual machine parameters:-xms10m (Minimum heap memory is 10MB),-xmx10m (maximum heap memory is 10MB, minimum heap memory and maximum heap memory are the same to avoid heap dynamic expansion),-xx:+ Heapdumponoutofmemoryerror can cause a Java virtual machine to take a snapshot of the current heap memory in case of a memory overflow for exception analysis.

The example code is as follows:

[Java]View Plaincopy
    1. public class  heapoom{  
    2.     static class oomobject{  
    3. }  
    4. span class= "keyword" >public static void main (string[ ] args) {  
    5.     list<oomobject > list = new arraylist<oomobject> ();   
    6.     while (true) {  
    7.     list.add (new oomobject ());   
    8. }  
    9. }&NBSP;&NBSP;
    10. }  

Running for a period of time will find that the OutOfMemoryError exception was generated and a heap memory exception dump file was generated.

(2). Java Virtual machine stack and local method stack overflow:

Since Sun's hotspot virtual machine does not differentiate between Java Virtual machine stacks and local method stacks, the-xoss parameter (setting the local method stack size) for a hotspot virtual machine exists, but is actually invalid, and the stack capacity can only be set by the-XSS parameter.

Because the Java Virtual machine stack is stackoverflowerror and outofmemoryerror two exceptions, use two examples to illustrate these two scenarios:

A.java virtual machine Stack depth overflow:

In a single-threaded environment, the virtual machine always throws a Stackoverflowerror exception when the memory is no longer allocated, either because the stack frame is too large or the VM stack capacity is too small. Use-xss128k to set the Java Virtual machine stack size to 128kb, the example code is as follows:

[Java]View Plaincopy
  1. Public class javavmstackof{
  2. private int stacklength = 1;
  3. public void Stackleak () {
  4. statcklength++;
  5. Stackleak ();
  6. }
  7. Public static void Main (string[] args) {
  8. Javavmstackof oom = new Javavmstackof ();
  9. Oom.stackleak ();
  10. }
  11. }

After running for a period of time, a Stackoverflowerror exception is generated. A Java Virtual machine stack Overflow typically occurs when the method recursively calls too much and the Java virtual machine stack has insufficient memory.

B.java virtual machine stack memory overflow:

Multi-threaded environment, the ability to create a thread maximum memory = physical memory-Maximum heap memory-maximum method area memory, in the Java Virtual machine stack memory, a single thread consumes more memory, the number of threads can be created smaller, so in the multithreaded condition it is easy to generate Java Virtual machine stack memory overflow exception.

Use the-XSS2M parameter to set the Java Virtual machine stack memory size to 2MB, the example code is as follows:

[Java]View Plaincopy
  1. Public class javavmstackoom{
  2. private void Dontstop () {
  3. While (true) {
  4. }
  5. }
  6. Public void Stackleakbythread () {
  7. While (true) {
  8. Thread t = new Thread (new Runnable () {
  9. public Void Run () {
  10. Dontstop ();
  11. }
  12. });
  13. T.start ();
  14. }
  15. }
  16. Public static void Main (string[] args) {
  17. Javavmstackoom oom = new Javavmstackoom ();
  18. Oom. Stackleakbythread ();.
  19. }
  20. }

After running for a period of time, the Java Virtual machine stack generates OUTOFMEMORYERROR because the memory is too small to create threads.

(3). Run a constant-rate pool overflow:

The run-time pool is part of the method area, and you can use-xx:permsize=10m and-xx:maxpermsize=10m to set the permanent maximum memory and minimum memory to 10MB size, and cannot be extended because the maximum memory and minimum memory size are the same for the permanent generation.

The string's intern () method is used to check the constant pool if there is a string equal to this string object, directly returning the strings object in the constant pool, otherwise, the string contained by this string object is added to the run-time pool and returns a reference to this string object. The Intern () method of the string is therefore particularly suitable for demonstrating a run-time pool overflow, as shown in the example code:

[Java]View Plaincopy
  1. Public class runtimeconstantpooloom{
  2. public static void Main (string[] args) {
  3. list<string> list = new arraylist<string> ();
  4. int i = 0;
  5. While (true) {
  6. List.add (String.valueof (i++). Intern ());
  7. }
  8. }
  9. }

Running for a period of time, the permanent generation of memory is not enough, running a constant pool due to the inability to add constants and generate OutOfMemoryError.

(4). Method Area Overflow:

The run-time constant pool is part of the method area, and they all belong to the permanent memory area in the hotspot virtual machine. The method area is used to store class information, Java's reflection and dynamic agent can dynamically generate class, in addition, third-party cglib can directly manipulate bytecode, can also dynamically generate class, experiment through cglib to demonstrate, the same use-xx:permsize= 10m and-xx:maxpermsize=10m will permanently set the maximum memory and minimum memory to 10MB size, and cannot be extended due to the same maximum memory and minimum memory size for the permanent generation. The example code is as follows:

[Java]View Plaincopy
  1. Public class javamethodareaoom{
  2. public static void Main (string[] args) {
  3. While (true) {
  4. Enhancer enhancer = new enhancer ();
  5. Enhancer.setsuperclass (oomobject.   Class);
  6. Enhancer.setusecache (false);
  7. Enhancer.setcallback (new Methodinterceptor () {
  8. Public Object Intercept (Object obj, Method method, object[] args,
  9. Methodproxy proxy)throws throwable{
  10. return Proxy.invokesuper (obj, args);
  11. }
  12. });
  13. Enhancer.create ();
  14. }
  15. }
  16. Class oomobject{
  17. }
  18. }

After running for a period of time, the permanent generation of memory is not enough, the method area can not be stored cglib create processing class information, Generate method area OutOfMemoryError.

(5). Native Direct Memory Overflow:

The Java Virtual machine can set the native direct memory available size through the parameter-xx:maxdirectmemorysize, if not specified, the default is the same size as the Java heap memory. The unsafe class can be obtained through reflection in the JDK (the unsafe getunsafe () method only starts the ClassLoader bootstrap to return the instance) and directly operates the native direct memory. By using-xx:maxdirectmemorysize=10m, limit the maximum available native direct memory size to 10MB, the example code is as follows:

[Java]View Plaincopy
  1. Public class directmemoryoom{
  2. private static final int _1mb = 1024* 1024x768 * 1024;
  3. PUBLC static void Main (string[] args) throws exception{
  4. Field Unsafefield = Unsafe.  class.getdeclaredfields () [0];
  5. Unsafefield.setaccessible (true);
  6. unsafe unsafe = (unsafe) unsafefield.get (null);
  7. While (true) {
  8. //unsafe directly to the operating system to request memory
  9. Unsafe.allocatememory (_1MB);
  10. }
  11. }
  12. }

When running for a period of time, the 10MB of native direct memory is assigned light and cannot produce outofmemoryerror when direct memory allocation is made.

(go) Deep understanding Java Virtual Machine Learning note 2--java Memory overflow instance

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.