The jdk1.5 version has added concurrent packages JUC
, one of which contains thread pools.
Four rejection strategies:
Deny Policy Type | illustrate | |
---|---|---|
1 | ThreadPoolExecutor.AbortPolicy | Default reject policy, reject task and throw task |
2 | ThreadPoolExecutor.CallerRunsPolicy | Run the task directly using the calling thread |
3 | ThreadPoolExecutor.DiscardPolicy | Reject the task directly without throwing an error |
4 | ThreadPoolExecutor.DiscardOldestPolicy | Trigger the rejection policy. As long as there are new tasks, the oldest task in the blocking queue will be discarded and new tasks will be added. |
preconfigured
Configure the thread pool.
- The core thread and the maximum thread are set as small as possible, set to 1 and 2 respectively
- Blocking queue sets a bounded queue of fixed length , with a length of 1
- The thread factory sets the default thread factory
// number of core threads int corePoolSize = 1; // maximum number of threads int maximumPoolSize = 2; // thread survival time long keepAliveTime = 10; // thread survival time unit TimeUnit unit = TimeUnit.SECONDS; // bounded queue follows FIFO Principle BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(1); // Thread Factory ThreadFactory threadFactory = Executors.defaultThreadFactory();
Create thread task
Create thread tasks, one thread task executes for one second:
class TaskThread implements Runnable{ private int i; public TaskThread(int i) { this.i = i; } @Override public void run() { try { TimeUnit.SECONDS.sleep(2); System.out.println("执行任务:" + i); } catch (InterruptedException e) { e.printStackTrace(); } } }
Rejection Policy One: AbortPolicy
Default reject policy, reject task and throw task
// Rejection policy The default rejection policy, rejects the task and throws an exception: RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy(); ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); for (int i = 1; i <= 5; i++) { try { threadPool.execute(new TaskThread(i)); } catch (Exception e) { System.out.println("[Task" + i + "]Error:" + e.getMessage()); } }
output
[Task] 4 Error: Task com.test.controller.ThreadPoolController$TaskThread@5c0369c4 rejected from java.util.concurrent.ThreadPoolExecutor@50675690[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0] [Task] 5 error: Task com.test.controller.ThreadPoolController$TaskThread@31b7dea0 rejected from java.util.concurrent.ThreadPoolExecutor@50675690[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0] perform tasks: 1 perform tasks: 3 perform tasks: 2
The maximum number of threads + blocking queue = 3, and an error is thrown when the execution reaches 4 and 5. You need to try catch
catch exceptions here. Tasks 1, 2, and 3 are executed normally.
If the submitted tasks are to be executed, the thrown error task can be stored in redis, and then the task redis
can be , and then submitted for execution.
Rejection Policy 2: CallerRunsPolicy
The calling thread runs redundant tasks.
To replace the rejection policy, replace the above AbortPolicy
with CallerRunsPolicy
.
RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
Execute the task, output:
Task: 1 Task: 4 Task: 3 Task: 2 Task: 5
The maximum number of threads + blocking queue = 3, and redundant tasks continue to be executed.
Rejection Policy Three: DiscardPolicy
Reject the task without throwing an error.
Replace the policy CallerRunsPolicy
with DiscardPolicy
:
RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();
Execute the task, output:
Task: 1 Task: 3 Task: 2
Excess thread task submissions are rejected, and only tasks up to the maximum number of threads + the number of blocking queues are executed without throwing an error.
Rejection Policy Four: DiscardOldestPolicy
As long as there are new tasks, the oldest task in the blocking queue will be discarded, and new tasks will be added to the blocking queue .
Replace the policy DiscardPolicy
with DiscardOldestPolicy
:
RejectedExecutionHandler handler3 = new ThreadPoolExecutor.DiscardOldestPolicy();
Execute the task, output:
Task: 3 Task: 1 Task: 5
The execution order of tasks is the number of core threads -> blocking queue -> the maximum number of threads, of which task 1 and task 3 are successfully submitted.
- Task 2 because it is in the blocking queue,
- The following task 4 squeezes out the task 2,
- Task 5 squeezes out task 4, so task 5 is executed last.
Summarize
This article introduces four thread rejection strategies. When the work task is larger than the maximum thread + blocking queue, the blocking queue will be executed.
- AbortPolicy default policy, reject the task, and throw an exception
- CallerRunsPolicy The calling thread executes the task for
- DiscardPolicy rejects the task without throwing an exception
- DiscardOldestPolicy has redundant tasks, discards the oldest task in the blocking queue and puts it into a new task until there are no new tasks.
If you think the article is helpful to you, please click on it!