2

The class below seems to consistently report 2542 threads being the maximum possible, irrespective of memory allocated to the app. What is limiting the number of threads here? Memory, CPU, internal JVM setting?

Thanks

public static void main(String... args) {

    int taskNumber = 0;
    while (true) {
        try {
            new MyThread().start();
        } catch (OutOfMemoryError e) {
            System.out.println("Thread " + taskNumber+" could not be created.");
            System.exit(0);
        }
        taskNumber++;
    }
}
Nicolas B
  • 115
  • 9
  • Most likely you have a 32-bit JVM and you are running out of virtual memory. Note: even if you have a 64-bit JVM, you might find the limit is around 32K due to a limit in the number of memory mappings allowed. In any case, you might find that having more threads than CPUs is actually slower, not faster, so use them wisely. – Peter Lawrey Mar 30 '14 at 15:39
  • Thanks Peter, good rule of thumb on the "more threads than CPU is slower". In this specific case, this is purely an academic exercise though ! – Nicolas B Mar 31 '14 at 02:34
  • In short, you are running out of a resource which is unlikely to be the heap. In fact if you are running low on virtual memory increasing the heap can leave less space for other things such as thread stacks. – Peter Lawrey Mar 31 '14 at 04:14

2 Answers2

4

Your opperating system has a limit of how many threads it can handle.

To get the number, execute the appropriate command on your machine:

Linux: sysctl kernel.threads-max

Mac OSX: sysctl kern.num_threads

ADDITION: Maybe you can find some interesting answers in this thread: How many threads can a Java VM support?

Community
  • 1
  • 1
Martin Seeler
  • 6,874
  • 3
  • 33
  • 45
  • 2
    @bluebrain no, Java uses the native OS thread mechanisms; at least all modern JVMs do (under Linux, that would be using `clone(2)`) – fge Mar 30 '14 at 12:43
  • 1
    You nailed it, tested for 32 bits and 64 JVM on OSX 10.6 JDK6 and 8. On my box, the limit is 2560 as per sysctl, so that's where my limitation comes from. os. – Nicolas B Sep 09 '16 at 08:18
2

For native threads the limit is in the underlying operating system resource allocation for the JVM process.

For green threads the limit is in the JVM implementation, but it runs on a single native thread.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347