线程oom后进程里其他线程还能运行吗?

参考 【原创】一个线程oom,进程里其他线程还能运行吗?

结论

线程OOM不会影响其他线程运行。

原因

OOM分很多种Understand the OutOfMemoryError Exception,此处演示的OOM 是java堆溢出。OOM异常发生于具体的线程上,发生OOM,说明该线程正在申请内存,受影响的线程局限于抛出异常的线程(daemon子线程除外)。而其他线程已经有足够内存,不需要再额外申请,所以不会受影响。且OOM后,受影响的线程因异常而退出,只被该线程所持有的资源不可达后,GC自动回收资源。

效果如图

在这里插入图片描述

启动参数

-XX:+PrintGCDetails -Xmn10m -Xmx32m -XX:+HeapDumpOnOutOfMemoryError -XX:+UseSerialGC -XX:+PrintHeapAtGC

示例代码

public class Test2 {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            new Thread(() -> {
                while (true) {
                    System.out.println(new Date().toLocaleString() + Thread.currentThread() + "==");
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            List<byte[]> list = new ArrayList<byte[]>();
            System.out.println(new Date().toString() + "wait...");
            try {
                Thread.sleep(3000);//尝试等待第一次gc日志
                System.out.println(new Date().toString() + "start...");
                int i = 0;
                while (true) {
                    System.out.println(new Date().toLocaleString() + Thread.currentThread() + ":"+(++i));
                    Thread.sleep(500);//方便打印出日志
                    int _1M = 1024 * 1024 * 1;
                    byte[] b = new byte[_1M];
                    list.add(b);
                    Thread.sleep(500);

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.setName("OOM-thread");
        thread.start();

    }
}

其他资料

Understand the OutOfMemoryError Exception
Java HotSpot VM Command-Line Options

原文地址:https://www.cnblogs.com/thewindkee/p/12873133.html