This test shows the max number of threads that can be created in Java
System.out.println("Max memory " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
for (int i = 0;; i++) {
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
};
};
try {
t.start();
} catch (Error e) {
System.out.println("Max threads " + i);
e.printStackTrace();
System.exit(1);
}
}
When I run it with default heap size (256M) I get
Max memory 247M
Max threads 2247
java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:691)
at test.Test1.main(Test1.java:19)
when I increase max heap size to 512M I get
Max memory 494M
Max threads 1906
...
when I increase max heap size to 1024M I get
Max memory 989M
Max threads 1162
...
That is, more heap memory fewer threads. Why is that?
java -version? - NPE