Java编程实现六种OOM
1、java.lang.OutOfMemoryError: Java heap space
jvm参数:-verbose:gc -XX:+PrintGCDetails -Xmx10M
示例代码:
public class OomTest {
public static void main(String[] args) {
heapOom();
}
/**
* java.lang.OutOfMemoryError: Java heap space
*/
private static void heapOom(){
List<OomTest> list = new ArrayList<>();
while (true){
list.add(new OomTest());
}
}
}
运行结果:

2、java.lang.OutOfMemoryError: unable to create new native thread
jvm参数:-verbose:gc -XX:+PrintGCDetails
示例代码:
public class OomTest {
public static void main(String[] args) {
threadOom();
}
/**
* java.lang.OutOfMemoryError: unable to create new native thread
*/
private static void threadOom() {
while(true) {
Thread thread = new Thread(() -> {
while (true) {
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
}
结果:

3、java.lang.StackOverflowError
jvm参数:-verbose:gc -XX:+PrintGCDetails -Xmx10M -Xss128K
示例代码:
public class OomTest {
public static void main(String[] args) {
stackOver();
}
private static int stackDep = 1;
public static void stackLeak(){
stackDep++;
stackLeak();
}
/**
* java.lang.StackOverflowError
*/
private static void stackOver(){
try {
stackLeak();
}catch (Throwable e){
e.printStackTrace();
System.out.println(OomTest.stackDep);
}
}
}
运行结果:


4、java.lang.OutOfMemoryError: Direct buffer memory
jvm参数:-verbose:gc -XX:+PrintGCDetails -Xmx10M
示例代码:
public class OomTest {
public static void main(String[] args) {
directBuffer();
}
/**
* java.lang.OutOfMemoryError: Direct buffer memory
*/
private static void directBuffer(){
final int _1M = 1024 * 1024 * 1;
List<ByteBuffer> buffers = new ArrayList<>();
int count = 1;
while (true) {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_1M);
buffers.add(byteBuffer);
System.out.println(count++);
}
}
}
运行结果:

5、java.lang.OutOfMemoryError: GC overhead limit exceeded
jvm参数:-verbose:gc -XX:+PrintGCDetails -Xmx10M
示例代码:
public class OomTest {
public static void main(String[] args) {
gcLimit();
}
/**
* java.lang.OutOfMemoryError: GC overhead limit exceeded
* -Xmx10M
*/
private static void gcLimit(){
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < Integer.MAX_VALUE; i++) {
executor.execute(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
}
运行结果:

6、MaxMetaspaceSize is too small
jvm参数:-XX:MaxMetaspaceSize=3M
示例代码:
public class OomTest {
public static void main(String[] args) {
metaspaceOom();
}
/**
* MaxMetaspaceSize is too small
* -XX:MaxMetaspaceSize=5M
*/
private static void metaspaceOom(){
List<Object> list = new LinkedList<>();
int temp = 0;
while(true){
temp++;
list.add(temp);
}
}
}
运行结果:

本文详细介绍了在Java编程中如何引发六种不同的OutOfMemoryError:Java堆空间不足、无法创建新的本地线程、堆栈溢出、直接缓冲区内存耗尽、GC开销限制超出以及元空间大小不足。每种情况都提供了相应的jvm参数配置和示例代码以模拟错误,帮助开发者理解和避免这些常见的内存问题。
2390

被折叠的 条评论
为什么被折叠?



