6

Running this code

        for (int i = 0; i < 4000; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                    }
                }
            }).start();
            System.out.println(i);
        }

results in

Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:658)
    at com.codeoverdrive.burnbearburn.Main.main(Main.java:10)

after 2024 running threads. Playing with JVM heap and stack sizes does not help.

sysctl kern.num_threads

returns

kern.num_threads: 10240

OS X Mountain Lion 10.8.4, Macbook Air with 4GB RAM

Any suggestions?

mixel
  • 25,177
  • 13
  • 126
  • 165

1 Answers1

3

The most probable cause is that the user you are running with has a limit on the number of threads it can create.

Try and increase this limit. The current limit can be shown by the ulimit -u command. Note that as a regular user you probably won't be able to increase it, you'll have to modify the environment as root.

And yes, OutOfMemoryError is misleading in this case.

fge
  • 119,121
  • 33
  • 254
  • 329
  • `ulimit -u` shows max users processes count, not threads. And I do not know why, but setting it does not changes it's value. – mixel Jun 13 '13 at 09:35
  • It also influences the number of threads! At least on Linux it does. And yes, it is normal that you cannot change it as a user. – fge Jun 13 '13 at 09:44