使用ThreadPoolExecutor产生的 OutOfMemoryError: unable to create new native thread 错误
轉載請注明出處:http://www.codelast.com/
最近,在使用Java的ThreadPoolExecutor來實現(xiàn)一個并發(fā)功能的時候,發(fā)現(xiàn)程序剛執(zhí)行起來不久,就提示了錯誤:
| 1 | OutOfMemoryError: unable to create new native thread |
并且服務器立即陷入類似于“無響應”的狀態(tài),無法用Ctrl+C結束掉我的Java程序,按Ctrl+C的時候,命令行只是不斷地打印出類似于下面的消息:
| 1 | Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated |
在其他已經連上的terminal下,我想嘗試用 ps -ef | grep xxx 來找出進程的pid并kill掉它,也無果,因為只要輸完ps命令,再一回車,馬上就提示錯誤(大概意思就是資源不足),于是在不重啟系統(tǒng)的情況下,只能靜靜等待,直到Linux系統(tǒng)恢復了響應,就可以用ps -ef查出其pid并kill掉它了。
文章來源:http://www.codelast.com/
但是為嘛會出現(xiàn)這樣的問題?
首先,服務器內存是非常充足的,不應該是內存真的不夠用;其次,我仔細檢查了一遍我的代碼,也并無異常之處;再次,我的程序也不會占用非常大的內存。
于是我問了一下Google,找到了原因所在:我程序中設置的ThreadPoolExecutor并發(fā)數(shù)超出了系統(tǒng)限制。這個限制,就是所謂的“max user processes”限制,可以用如下命令查看Linux系統(tǒng)的設置值:
| 1 | ulimit -a |
其輸出類似于:
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | core file size????????? (blocks, -c) 0 data seg size?????????? (kbytes, -d) unlimited scheduling priority???????????? (-e) 0 file size?????????????? (blocks, -f) unlimited pending signals???????????????? (-i) 385903 max locked memory?????? (kbytes, -l) 64 max memory size???????? (kbytes, -m) unlimited open files????????????????????? (-n) 65535 pipe size??????????? (512 bytes, -p) 8 POSIX message queues???? (bytes, -q) 819200 real-time priority????????????? (-r) 0 stack size????????????? (kbytes, -s) 10240 cpu time?????????????? (seconds, -t) unlimited max user processes????????????? (-u) 1024 virtual memory????????? (kbytes, -v) unlimited file locks????????????????????? (-x) unlimited |
看到“max user processes”那一行了嗎?1024就是我當前用戶的最大允許值,當超過這個值的時候,就無法創(chuàng)建新的process了。
文章來源:http://www.codelast.com/
對應到使用ThreadPoolExecutor的代碼,當我們創(chuàng)建一個對象的時候,會使用如下的構造函數(shù):
| 1 2 3 4 5 | public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, ??????????????????????????????long keepAliveTime, TimeUnit unit, ??????????????????????????????BlockingQueue<Runnable> workQueue) { ????//... } |
其中,第1和第2個參數(shù),就是線程池里線程數(shù)的大小:
@param corePoolSize the number of threads to keep in the pool, even if they are idle.
@param maximumPoolSize the maximum number of threads to allow in the pool.
雖然我只把這兩個數(shù)值分別設置成了400和500,但是由于我的用戶下還運行有其他很多程序,因此,它們加在一起占用的線程數(shù)超過了1024的時候,就會出現(xiàn)前面的錯誤。
文章來源:http://www.codelast.com/
要修改Linux系統(tǒng)中的這個限制,可以修改?/etc/security/limits.d/90-nproc.conf?文件,其內容類似于:
| 1 2 3 4 5 6 | # Default limit for number of user's processes to prevent # accidental fork bombs. # See rhbz #432903 for reasoning. ? *????????? soft??? nproc???? 1024 root?????? soft??? nproc???? unlimited |
把里面的數(shù)值改掉即可。
由于不方便修改Linux系統(tǒng)配置,因此,我把ThreadPoolExecutor的線程數(shù)調小到100,發(fā)現(xiàn)程序運行起來再也沒有出現(xiàn)過上面的問題,非常穩(wěn)定。
總結
以上是生活随笔為你收集整理的使用ThreadPoolExecutor产生的 OutOfMemoryError: unable to create new native thread 错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决 - java.lang.OutOf
- 下一篇: 眼皮有时单有时双怎么办