第一讲JVM内存四大类型:Heap,Stack,Contant,DirectMemory等
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");
Listpersons = 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 classHelloStackOverFlow {
private int counter;
publicvoidcount()
{
counter++;
count();
}
public static void main(String[] args)
{
System.out.println("HelloStackOverFlow");
HelloStackOverFlow helloStackOverFlow=
newHelloStackOverFlow();
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 classHelloDirectMemoryOutOfmemory {
private static final int ONE_GB =
1024*1024*1024;
private staticintcount=
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