Thread pool principle of Java concurrency thread pool (4)_ Power node Java college sorting

Introduction to rejection policy

The rejection policy of thread pool refers to the processing measures taken when a task is rejected when it is added to the thread pool.

When a task is added to the thread pool, it may be rejected because: first, the thread pool closes abnormally. Second, the number of tasks exceeds the maximum limit of the thread pool.

The thread pool includes four rejection policies: abortpolicy, callerrunspolicy, discardoldestpolicy and discardpolicy.

The default processing policy of thread pool is abortpolicy!

Rejection policy comparison and example

The following illustrates four rejection policies of thread pool through examples.

1. Example of discardpolicy

Operation results:

The results show that the "maximum pool size" and "core pool size" of the thread pool are both 1 (threads_size), which means that "the maximum number of tasks that the thread pool can run at the same time can only be 1".

The blocking queue of thread pool pool is arrayblockingqueue. Arrayblockingqueue is a bounded blocking queue. The capacity of arrayblockingqueue is 1. This also means that the thread pool blocking queue can only have one thread pool blocking waiting.

According to the execute() code analyzed in '', there are two tasks running in the thread pool. The first task is directly put into the worker and executed through threads; The second task is placed in the blocking queue and waits. Other tasks have been discarded!

2. Example of discardoldestpolicy

Operation results:

Result description: after changing the "rejection policy of thread pool" from discardpolicy to discardoldestpolicy, when a task added to the thread pool is rejected, the thread pool will discard the task at the end of the blocking queue, and then add the rejected task to the end.

3. Abortpolicy example

(a) operation result:

Result description: after changing the "rejection policy of thread pool" from discardpolicy to abortpolicy, rejectedexecutionexception will be thrown when a task added to the thread pool is rejected.

4. Callerrunspolicy example

(a) operation result:

Result description: after changing the "rejection policy of thread pool" from discardpolicy to callerrunspolicy, when a task is added to the thread pool and rejected, the thread pool will add the rejected task to the "running threads of thread pool" for running

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>