Search code examples
javaandroidjava-threads

Running too many threads - java.lang.OutOfMemoryError


I'm creating too many threads like this in my App for some testing purposes , but sometimes when i set the number of thread too high it crash with a

java.lang.OutOfMemoryError:
at java.lang.Thread.nativeCreate (Thread.java)
at java.lang.Thread.start (Thread.java:731)


new Thread(new Runnable() {
            @Override
            public void run() {
                while (!stop) {

                }
            }
        }).start();

How to prevent this bug ? Or how to solve it ? Maybe a Try - Catch can make any work ?


Solution

  • To explain why does the JVM thrown an OOM when creating too many threads, the reason is that each thread allocates memory for its own stack. Memory is limited and so are the number of threads. How big is a thread's stack by default depends on your JVM, on Hotspot I believe it's ~1M, but no idea on Android. You should be able to check with: java -XX:+PrintFlagsFinal -version | grep ThreadStackSize. This setting can be controlled with the -Xss parameter.

    The solution is to lower memory usage by threads. You can do this by reducing the stack sizes for each thread with the -Xss value, and by reducing the number of threads that you create. How many you can afford will depend on memory available to the JVM on the host, after discounting memory consumed by the heap, other regions, and JVM internals. Roughly (Total memory - (all memory used by the jvm)) / -Xss.

    Of course, using Executors as suggested in other answers helps you define a pool with a limited number of threads, and submit work to it (as opposed to creating unlimited threads.)