在linux中,每个登录用户的每个进程都有一个最大打开文件的限制,如下所示:
$ ulimit -n
1024
当我学习java nio时,我想检查这个值。因为channel也是Linux中的一个文件,所以我编写了一个客户端代码来继续创建socketChannel,直到抛出异常:
java.net.SocketException: Too many open files
at sun.nio.ch.Net.socket0(Native Method)
at sun.nio.ch.Net.socket(Net.java:423)
at sun.nio.ch.Net.socket(Net.java:416)
at sun.nio.ch.SocketChannelImpl.<init>(SocketChannelImpl.java:104)
at sun.nio.ch.SelectorProviderImpl.openSocketChannel(SelectorProviderImpl.java:60)
at java.nio.channels.SocketChannel.open(SocketChannel.java:142)
但我发现它直到创建了大约4085个socketChannel,它会抛出这个异常。这个数字超过1024.有人告诉我jvm隐含地改变了这个值。我写了一个java程序来执行ulimit命令,发现jvm确实改变了这个值。如下:
String [] cmdArray = {"sh","-c","ulimit -n"};
Process p = Runtime.getRuntime().exec(cmdArray);
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.println(new String(buf, 0, len)); //4096
有人知道jvm何时何地以及如何更改此值?是否存在一些用于记录此更改的sys日志,或者某些sys工具是否可以监视此更改?
答案 0 :(得分:2)
$ strace -f -o HelloWorld.strace java HelloWorld
Hello World!
$ vi HelloWorld.strace
...
16341 getrlimit(RLIMIT_NOFILE, {rlim_cur=1024, rlim_max=4*1024}) = 0
16341 setrlimit(RLIMIT_NOFILE, {rlim_cur=4*1024, rlim_max=4*1024}) = 0
...
下载openjdk,然后cd进入hotspot目录,
$ grep -r setrlimit
...
src/os/linux/vm/os_linux.cpp: status = setrlimit(RLIMIT_NOFILE, &nbr_files);
...
$ vi src/os/linux/vm/os_linux.cpp
...
if (MaxFDLimit) {
// set the number of file descriptors to max. print out error
// if getrlimit/setrlimit fails but continue regardless.
struct rlimit nbr_files;
int status = getrlimit(RLIMIT_NOFILE, &nbr_files);
if (status != 0) {
if (PrintMiscellaneous && (Verbose || WizardMode))
perror("os::init_2 getrlimit failed");
} else {
nbr_files.rlim_cur = nbr_files.rlim_max;
status = setrlimit(RLIMIT_NOFILE, &nbr_files);
if (status != 0) {
if (PrintMiscellaneous && (Verbose || WizardMode))
perror("os::init_2 setrlimit failed");
}
}
...
如果修改上述代码,例如
//nbr_files.rlim_cur = nbr_files.rlim_max;
nbr_files.rlim_cur = 2048;
然后重建这个openjdk,然后用这个新的jdk执行上面的代码,你会发现输出是2048。