線程oom後進程裏其他線程還能運行嗎?

參考 【原創】一個線程oom,進程裏其他線程還能運行嗎?

結論

線程OOM不會影響其他線程運行。

原因

OOM分很多種Understand the OutOfMemoryError Exception,此處演示的OOM 是java堆溢出。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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章