17
votes

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?

2
Could we see your java -version? - NPE
It is HotSpot(TM) Client VM 1.7.0_21 on Windows 7 - Evgeniy Dorofeev
More threads = less heap - Yousha Aleayoub

2 Answers

18
votes

Each thread requires a stack. The more memory you allocate to the heap, the less memory is left for the stacks.

This will be particularly acute if you're using a 32-bit JVM, since the process will have no more than 4GB of address space for everything (the code, the heap, the stacks etc). I cannot reproduce this behaviour on my 64-bit box, where "Max threads" remains the same regardless of how much memory I allocate to the heap.

It is worth noting that many operating systems enable you to tweak the size of the stack. On Unix this is done using ulimit -s.

0
votes

I'm guessing that increasing the heap size (and using all of it) lowers the amount of memory the OS has available for creating new threads, so it can't create as many threads as before.