不知何故,我無法在MacBook上從Java打開超過10223個文件,而使用sysctl,launchd和ulimit打開的文件限制設置爲65535,我可以從C程序打開62282個文件。OS X上是否存在Java特定的打開文件限制?
您是否知道Java是否存在一些額外的限制,以及如何改變它?
我用來測試的Java代碼是:
import java.io.*;
import java.util.*;
class OpenFilesTest {
private static List<InputStream> streams = new ArrayList<InputStream>();
public static void main(String[] args) {
for (int i = 0; true; i++) {
FileInputStream f = null;
try {
f = new FileInputStream("/dev/null");
} catch (Throwable e) {
System.err.println(e.getMessage());
e.printStackTrace();
System.exit(1);
}
streams.add(f);
System.out.println("We have " + (i + 1) + " InputStream's for /dev/null");
}
}
}
這個輸出:
We have 1 InputStream's for /dev/null
We have 2 InputStream's for /dev/null
We have 3 InputStream's for /dev/null
...
We have 10221 InputStream's for /dev/null
We have 10222 InputStream's for /dev/null
We have 10223 InputStream's for /dev/null
/dev/null (Too many open files)
java.io.FileNotFoundException: /dev/null (Too many open files)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at OpenFilesTest.main(test.java:11)
我用於測試的C代碼:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main(void)
{
for (int i = 0; 1; i++)
{
int fd = open("/dev/null", O_RDONLY);
if (fd == -1)
{
perror("Couldn't open /dev/null one more time");
exit(EXIT_FAILURE);
} else {
printf("Opened /dev/null %d times\n", i + 1);
}
}
}
和其輸出:
Opened /dev/null 1 times
Opened /dev/null 2 times
Opened /dev/null 3 times
...
Opened /dev/null 62287 times
Opened /dev/null 62288 times
Opened /dev/null 62289 times
Couldn't open /dev/null one more time: Too many open files in system
有關係統的一些更多的相關信息:
$ uname -a
Darwin hostname.local 13.1.0 Darwin Kernel Version 13.1.0: Thu Jan 16 19:40:37 PST 2014; root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64
$ java -version
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b15)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
我自己也嘗試這種在Linux(Debian的喘息7.4),並在那裏我可以開接近65535頁的文件句柄也是用這個Java程序。
如此多的打開文件的底層用例是Scala中的服務器負載測試應用程序。
恕我直言,對於(int i = 0; true; i ++)'真的很醜。如果你喜歡,爲什麼不只是'while(true)'或'for(;;)'? – halex
@halex因爲操作需要一個計數器。無論如何,這是一個一蹴而就的測試程序,其中這些細節完全不相關。 – nos