首頁 > 軟體

Java中ThreadLocal 導致記憶體 OOM 的原因分析

2022-05-20 13:12:00

原因分析

ThreadLocal 導致記憶體 OOM 的原因是什麼?

ThreadLocal 底層通過 ThreadLocalMap 儲存資料

原始碼如下: 

  • 當我們使用ThreadLocal.set()時,set的value與key(即業務自己定義的ThreadLocal類)會儲存在ThreadLocalMap的Entry[]陣列裡

原始碼如下:

  • 其中Entry是實現了一個弱參照WeakReference,Entry的key(即業務方定義的 ThreadLocal類)會被包裝成一個弱參照當成Entry的key。Java的弱參照的定義是,當JVM執行垃圾回收掃描的時候,當發現只有弱參照的物件時,會立即回收此物件,這是ThreadLocal當初設計的時候防止記憶體溢位的一個手段

原始碼如下: 

雖然key被包裝成了一個弱參照會被垃圾回收機制給回收,但是value線上程(Thread)不死亡時卻可能存在一條強參照鏈.

由於 value是強參照,只要 Thread不死亡時,例如執行緒池,這條強參照鏈就會存在,那麼value就不會回收,可能造成記憶體溢位

參照關係如下: Thread ==> ThreadLocalMap ==> Entry ==> value

但是這個消除強參照鏈的動作是需要業務方在get的情況下觸發的,可能業務方並不會get、也可能get是key不為空,並不會觸發 expungeStaleEntry 類。所以開發者要養成良好的習慣,記得用完 ThreadLocal 時,調一次ThreadLocal.remove()方法或者 ThreadLocal.set(null)

正確的使用方式

public class ThreadLocalTest {
    /**
     * 未初始化的本地執行緒變數
     */
    private static ThreadLocal<User> userThreadLocal = new ThreadLocal<>();
    public static void main(String[] args) throws InterruptedException {
        int threadNum = 10;
        List<Thread> threadList = Lists.newArrayList();

        for (int i = 0; i < threadNum; ++i) {
            long userId = i;
            Thread t = new Thread(() -> {
                try {
                    // 設定變數值
                    userThreadLocal.set(new User(userId, "lanxing" + userId, "2x"));
                    // 使用變數
                    doSomething();
                } finally {
                    // 移除變數
                    userThreadLocal.remove();   //移除ThreadLocal變數
                }
            }, "T" + i);
            threadList.add(t);
            t.start();
        }

        for (int i = 0; i < threadNum; ++i) {
            threadList.get(i).join();
        }
    }
    private static void doSomething() {
        log.info("Use ThreadLocal variable :{}", JSON.toJSONString(userThreadLocal.get()));
    }
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
    private Long id;
    private String name;
    private String level;
}

列印結果:

14:30:26.790 [T2] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":2,"level":"2x","name":"lanxing2"}
14:30:26.789 [T5] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":5,"level":"2x","name":"lanxing5"}
14:30:26.792 [T0] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":0,"level":"2x","name":"lanxing0"}
14:30:26.792 [T4] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":4,"level":"2x","name":"lanxing4"}
14:30:26.792 [T8] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":8,"level":"2x","name":"lanxing8"}
14:30:26.791 [T1] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":1,"level":"2x","name":"lanxing1"}
14:30:26.792 [T7] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":7,"level":"2x","name":"lanxing7"}
14:30:26.792 [T6] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":6,"level":"2x","name":"lanxing6"}
14:30:26.791 [T9] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":9,"level":"2x","name":"lanxing9"}
14:30:26.790 [T3] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":3,"level":"2x","name":"lanxing3"}

到此這篇關於Java中ThreadLocal 導致記憶體 OOM 的原因分析的文章就介紹到這了,更多相關Java 記憶體OOM 內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com