I am trying to continuously start new threads with Java for testing purposes. Here is my code.
import java.util.TimerTask;
import java.util.Timer;
class MakeNewThreads extends TimerTask {
    public static long threadNum=0;
    public void run() {
        Thread thread = new Thread(){
            public void run(){
                try {
                    threadNum++;
                    System.out.println(threadNum);
                    Thread.sleep(10000000);
                } catch(InterruptedException e) { }
            }
        };
        thread.start();
    }
}
public class Main {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new MakeNewThreads(), 0, 100);
    }
}
However, I meet with the following error before I hit the maximum user process limit.
Exception in thread "Timer-0" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:714)
    at MakeNewThreads.run(Main.java:16)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)
I have checked the user process limit by ulimit -u. The result is 81920, but I can only create about 11000 threads before I meet with java.lang.OutOfMemoryError. In addition, if I set the user process limit to be lower manually, like 1000, I still cannot even approach the limit (I can create around 400 threads in this case). What could be possible reasons for this? Thanks in advance.
Update 1: I have tried methods mentioned in How to increase maximum number of JVM threads (Linux 64bit)
- I tried the sample program in this page. The result is around 11832. 
- I have tried to run the program with - -Xss256K -Xmx1G. The result does not change.
- ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 127051 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 81920 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
- cat /proc/sys/kernel/threads-max 254103
- cat /proc/sys/kernel/pid_max 4194303
- cat /proc/sys/vm/max_map_count 262144
Update 2: The problem seems to be solved. When I set the user process limit to 7000. I can create around 7000 threads. I suppose previously it is still the memory problem, but I cannot understand why I can only create up to 11000 threads since 11000*256/1024/1024=2.7G, which is far below the total memory, 32G, of my desktop. I don't think other background threads can take up 30G. Could anyone explain this? Thanks for all the help.
