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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值