java newFixedThreadPool 報錯

前言: 最近在開發一個web服務 jersey + glassfish
服務的流程大致是這樣,通過Restfull 接口接收請求,創建任務推給 由newFixedThreadPool() 創建的線程進行消費。運行一段時間後,發現程序報如下錯誤

Exception in thread "pool-2-thread-161" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:714)
    at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:950)
    at java.util.concurrent.ThreadPoolExecutor.processWorkerExit(ThreadPoolExecutor.java:1018)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1160)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

排查問題:
首先使用jstat 看jvm的內存使用情況

jstat -gcutil 22125 100

發現內存使用情況良好,本來嘗試使用jstack 打印
考慮到是ThreadPoolExecutor 爆出的錯誤,查看文檔發現如下的說明

public static ExecutorService newFixedThreadPool(int nThreads,
                                ThreadFactory threadFactory)
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue, using the provided ThreadFactory to create new threads when needed. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

如果原來的線程因爲某種原因執行失敗,線程池將會補充新的線程,整個線程池中線程的數量會超過nThreads, 導致系統資源耗盡

我把newFixedThreadPool() 替換成了newSingleThreadExecutor()
問題解決,希望對其他人有所幫助。

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