Thread Pool of Oracle Official Concurrency Tutorial

Thread Pool of Oracle Official Concurrency Tutorial

 

Most executor implementations in the java.util.concurrent package use a thread pool composed of worker threads, which are independent of the Runnable and Callable tasks they execute, and are often used to execute multiple tasks.

Using worker threads minimizes the overhead of creating threads. In large-scale concurrent applications, creating a large number of Thread objects will occupy a large amount of system memory, and allocating and reclaiming these objects will generate a lot of overhead.

 

One of the most common thread pools is a fixed-size thread pool. This thread pool always has a certain number of threads running. If a thread terminates for some reason, the thread pool will automatically create a new thread to replace it. Tasks that need to be executed are submitted to threads through an internal queue, which holds additional tasks when no more worker threads are available to execute tasks.

An important benefit of using a fixed-size thread pool is graceful degradation. For example, a web server, where each HTTP request is handled by a separate thread, if a new thread is created for each HTTP, then when the overhead of the system exceeds its capacity, it will suddenly stop responding to all requests . If you limit the number of threads a web server can create, then it doesn't have to process all incoming requests at once, but only when it's able to.

The easiest way to create an executor that uses a thread pool is to call java.util.concurrent.Executorsthe newFixedThreadPoolmethod. The Executors class also provides the following methods:

  • newCachedThreadPoolmethod creates an extensible thread pool. Good for applications that start many short tasks.
  • newSingleThreadExecutorThe method creates an executor that executes one task at a time.
  • There are also methods for creating ScheduledExecutorService executors.

If none of the above methods meet your needs, you can tryjava.util.concurrent.ThreadPoolExecutor或者java.util.concurrent.ScheduledThreadPoolExecutor

Original article, please indicate when reprinting: Reprinted from Concurrent Programming Network – ifeve.com Link to this article: Thread Pool of Oracle Official Concurrency Tutorial

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326226032&siteId=291194637