浅谈系统线程数限制

本文探讨了Linux系统中线程创建的限制,包括内存大小、ulimit、sys.kernel.threads-max、sys.kernel.pid_max、sys.vm.max_map_count及cgroup等。当Java线程创建失败时,可能由于内存不足或系统限制导致。通过ulimit命令和系统配置文件可调整限制,而cgroup则用于控制进程的资源使用。
摘要由CSDN通过智能技术生成

Linux进程与线程

概念就不提了,Richard Stevens的描述:
>
fork is expensive. Memory is copied from the parent to the child, all descriptors are duplicated in the child, and so on. Current implementations use a technique called copy-on-write, which avoids a copy of the parent’s data space to the child until the child needs its own copy. But, regardless of this optimization, fork is expensive.
IPC is required to pass information between the parent and child after the fork. Passing information from the parent to the child before the fork is easy, since the child starts with a copy of the parent’s data space and with a copy of all the parent’s descriptors. But, returning information from the child to the parent takes more work.
Threads help with both problems. Threads are sometimes called lightweight processes since a thread is “lighter weight” than a process. That is, thread creation can be 10–100 times faster than process creation.
All threads within a process share the same global memory. This makes the sharing of information easy between the threads, but along with this simplicity comes the problem.

Linux中创建进程用fork操作,线程用clone操作。通过ps -ef看到的是进程列表,线程可以通过ps -eLf来查看。
用top命令的话,通过H开关也可以切换到线程视图。

具体到Java线程模型,规范是没有规定Java线程和系统线程的对应关系的,不过目前常见的实现是一对一的。
参考http://openjdk.java.net/groups/hotspot/docs/RuntimeOverview.html#Thread%20Management|outline

问题排查思路

如果创建不了Java线程,报错是

Exception in thread “main” java.lang.OutOfMemoryError: unable to create new native thread

下面是常见的问题原因:

内存太小

在Java中创建一个线程需要消耗一定的栈空间,默认的栈空间是1M(可以根据应用情况指定-Xss参数进行调整),栈空间过小或递归调用过深,可能会出现StackOverflowError。

对于一个进程来说,假设一定量可使用的内存,分配给堆空间的越多,留给栈空间的就越少。这个限制常见于32位Java应用,进程空间4G,用户空间2G(Linux下3G,所以通常堆可以设置更大一些),减去堆空间大小(通过-Xms、-Xmx指定范围),减去非堆空间(其中永久代部分通过PermSize、MaxPermSize指定大小,在Java8换成了MetaSpace,默认不限制大小),再减去虚拟机自身消耗,剩下的就是栈空间,假设剩下300M,那么理论上就限制了只能开300线程。不过对于64位应用,由于进程空间近乎无限大,所以可以不考虑这个问题。

ulimit限制

线程数还会受到系统限制,系统限制通过ulimit -a可以查看到。

https://ss64.com/bash/ulimit.html

caixj@Lenovo-PC:~$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7823
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值