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