Why does ScheduledThreadPoolExecutor only accept a fixed number of threads?

前端 未结 3 1895
盖世英雄少女心
盖世英雄少女心 2020-12-13 09:21

I may imagine some tasks scheduled to take a very long time and ScheduledThreadPoolExecutor would create additional threads for the other tasks that need to be

3条回答
  •  别那么骄傲
    2020-12-13 10:02

    According to Java Concurrency In Practice there are the following disadvantages of unbounded thread creation:

    Thread lifecyle overhead

    Thread creation and teardown are not free. Thread creation takes time, and requires some processing activity by the JVM and OS.

    Resource consumption

    Active threads consume system resources, especially memory. When there are more runnable threads than available processors, threads sit idle. Having many idle threads can tie up a lot of memory, putting pressure on the garbage collector, and having many threads competing for the CPUs can impose other performance costs as well. If you have enough threads to keep all the CPUs busy, creating more threads won't help and may even hurt.

    Stability

    There is a limit on how many threads can be created. The limit varies by platform and is affected by factors including JVM invocation parameters, the requested stack size in the Thread constructor, and limits on threads placed by the underlying operating system. When you hit htis limit, the most likely result is an OutOfMemoryError. Trying to recover from such an error is very risky; it is far easier to structur your program to avoid hitting this limit.


    Up to a certain point, more threads can improve throughput, but beyond that point creating more threads just slows down your application, and creating one thread too many can cause your entire application to crash horribly. The way to stay out of danger is to place some bound on how many threads your application creates, and to test your application thoroughly to ensure that, even when this bound is reached, it does not run out of resources.

    Unbounded thread creation may appear to work just fine during prototyping and development, with problems surfacing only when the application is deployed and under heavy load.

提交回复
热议问题