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()
问题解决,希望对其他人有所帮助。

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