1. 程式人生 > >JVM內存四大類型:Heap,Stack,Contant,DirectMemory等

JVM內存四大類型:Heap,Stack,Contant,DirectMemory等

class style 開發 方法 tac limit IT created cep

技術分享圖片

Stack屬於棧的區域,屬於每條線程私有的。

方法區和本地方法棧有很大的不同,方法區是用Java級別角度做的代碼,本地方法棧指向的是C/C++。

Java開發,對象就在堆中,一般而言,堆中只有對象。

堆溢出測試:程序運行設置:-verbose:gc -Xms10M -Xmx10M -Xss128k -XX:+PrintGCDetails
package com.dt.spark.jvm.basics;

import java.util.ArrayList;

import java.util.List;

class Person{ }

public class HelloHeapOutOfMemory {

         
public static void main(String[] args) { System.out.println("HelloHeapOutOfMemory"); List persons = new ArrayList(); int counter = 0; while(true){ persons.add(new Person()); System.
out.println("Instance: " + (++counter)); } } }
報錯:Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

棧溢出測試:

package com.dt.spark.jvm.basics;

public class  HelloStackOverFlow {

    private int counter;

    public void count() {

       counter++;
 
       count();

    }

    
public static void main(String[] args) { System.out.println("HelloStackOverFlow"); HelloStackOverFlow helloStackOverFlow= new HelloStackOverFlow(); try { helloStackOverFlow.count(); } catch(Exception e) { e.printStackTrace(); throw e; } } }
報錯:Exception in thread "main" java.lang.StackOverflowError

常量區溢出報錯測試

package com.dt.spark.jvm.basics;

import java.util.ArrayList;

import java.util.List;

public class HelloConstantOutOfMemory {

         public static void main(String[] args) {

                    try {

                    List stringList = new ArrayList();

                    int item = 0;

                    while(true){

                       stringList.add(String.valueOf(item++).intern());

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                    throw e;

                }

         }

}
報錯:Exception in thread "main" [Full GC (Ergonomics) java.lang.OutOfMemoryError: GC overhead limit exceeded

DirectMemory溢出報錯測試:

package com.dt.spark.jvm.basics;

import java.nio.ByteBuffer;

public class HelloDirectMemoryOutOfmemory {

    private static final int ONE_GB = 1024*1024*1024;

     private static int count= 1;

    public static void main(String[] args) {

          try {          

               while (true) {

                  ByteBuffer buffer = ByteBuffer.allocateDirect(ONE_GB);

                  count++;
               }

           } catch (Exception e) {

               System.out.println("Exception:instance created "+count);

               e.printStackTrace();

           } catch (Error e) {

               System.out.println("Error:instance created "+count);

               e.printStackTrace();

           }
    }

}
報錯:java.lang.OutOfMemoryError: Direct buffer memory

JVM內存四大類型:Heap,Stack,Contant,DirectMemory等