Java concurrent programming combat reading notes: the use of thread pools

Coupling between tasks and strategies

As mentioned above, java decouples the execution and submission of tasks through the excutor framework. In fact, there is a certain coupling between tasks and execution strategies. Not all tasks can use arbitrary execution strategies. For example, a task depends on other tasks, tasks that can only be executed in one thread, and tasks that are particularly sensitive to response (GUI). These tasks cannot be slaved by ordinary thread pools, but need to customize the corresponding execution strategy for the task. Thread pools work best when tasks are independent of each other and of the same type

thread starvation deadlock

When a task in the thread pool depends on other tasks, a deadlock may occur. If the task is in the single-threaded thread pool, the size of the thread pool is not large enough, or all depend on limited resources (such as the JDBC connection pool), the Deadlock may occur due to waiting

Long-running tasks

If some tasks in the thread pool run for a long time, and the size of the thread pool is not large enough, the thread pool will be unresponsive for a short time.

Set the size of the thread pool

The size of the thread pool can be set according to the execution of the application. For the CPU-intensive type, you can set the number of threads to be the number of CPUs + 1. For the IO-intensive type, you can set more. You can set the thread pool size by observing the CPU usage in advance.

Configure thread pool

Manage task queues

In the thread pool, you can manually set the task queue, such as using a bounded queue, synchronous queue (submit while assigning thread execution, rather than putting it in the queue)

saturation strategy

When the queue in the thread pool is full, the execution strategy is the saturation strategy, which can directly reject the task submission, or discard the oldest one, or directly use the calling thread to run, which will cause the calling thread to suspend submission due to running tasks.

thread factory

You can customize the thread factory in the thread pool, so that the thread pool can create the threads you need, such as the thread's uncaughtexceptionhandler, print logs, statistics, and thread names

Guess you like

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