Objective
The thread pool can improve the concurrency of the program (which, of course, is appropriate) because there are a number of drawbacks to creating a new thread for each commit task without a thread:
1. The cost of creating and destroying threads is very high, and the creation of threads takes time, delays the execution of tasks, and consumes a lot of system resources.
2. An active thread consumes system resources, and a large number of idle threads consume a lot of memory, which can put a lot of pressure on the garbage collector, while a large number of threads will incur the performance overhead of gas when competing for CPU resources.
3. The system has a limit on the threads that can be created, and if this limit is exceeded, oom is likely to be thrown.
It is not difficult to see that, in a certain range, increasing the thread can increase the throughput of the system, and when the number of threads exceeds a reasonable value, the increased thread will slow down the execution of the program.
Introduction of Executor
In JDK1.5, we introduced a thread pool framework, executor framework, which can decompose the creation and execution of tasks. It includes executor, Executorservice, callable and other interfaces and executors, Threadpoolexecutor implementation classes.
Watch out.
Of course, it takes a dialectic to look at things, and if you use the executor framework, you can decouple complex task execution nicely. This way we actually need to limit the scope of its use.
- For dependent tasks, it is not very appropriate to use the thread pool to operate and to trigger deadlocks, because in this case we need to be careful to maintain the order in which these tasks are executed to ensure that no deadlock is triggered.
- The use of single-threaded executor can guarantee more secure concurrency for thread-safe tasks that are threaded-gated.
- Use Threadlocal's task because the thread pool will reuse threads, which will cause the threadlocal value of the task to be meaningless (unless the thread-local value is limited to the life cycle of the task).
- For response time-sensitive tasks, it is assumed that we will slow down the program's responsiveness by placing a task that takes a long time to execute, or when multiple, long-executing tasks are placed in a single-threaded executor or a thread pool with a small number of threads.
The appropriate number of threads
The thread pool achieves the best performance when dealing with tasks of the same type and is independent of each other, otherwise the task's long inconsistency can easily cause congestion or starvation.
The number of threads in that thread pool is appropriate, and for computationally intensive tasks, we'd better set the number of threads = number of CPUs +1, (+1 is to ensure that when a thread pauses for a fault or other reason, this +1 thread can ensure that the CPU's clock cycle is not wasted) , and for tasks that include IO operations or other blocking operations, the thread pool should be larger in size because the threads do not always execute.
Use of the thread pool
In the actual use of the process, we generally rely on threadpoolexecutor to complete the thread pool creation. The Threadpoolexecutor has excellent extensibility, in addition to the four commonly used thread pools provided by the system, such as Cachedthreadpoolexecutor,fixedthreadpoolexecutor, Singlethreadpoolexecutor,scheduledthreadexecutor. We can customize the thread pool's constructors, such as the thread pool's basic thread count, the maximum number of threads, the thread pool's timeout (time + time unit), the Threads Pool's task queue, the threading factory of the thread pool, and the saturation policy of the thread pool.
Of course, when we use the four thread pools provided by the system, we can also modify the thread pool configuration later.
Task Queue for threads
Linkedblockqueue: Default task queue for unbounded Cachedthreadpoolexecutor Fixedthreadpoolexecutor
Arrayblockqueue: Bounded
Priorityqueue: Priority queue, default task queue for bounded scheduledthreadpoolexecutor
Synchronousqueue: Synchronous handover with a queue capacity of 0 and the task is only placed in the queue when the thread is ready.
Saturation strategy
Settings for saturation policy
In the case of bounded queues, when the bounded queue is filled, we need to use the thread's saturation policy, which we can then configure to set up the thread pool later. The saturation strategy is modified by Threadpoolexecutor's Setrejectedexecutionhandler method (when a task is submitted to a executor that has been closed, the saturation strategy is used)
The saturation strategy mainly has the following kinds: AbortPolicy, Callerrunspolicy, Discardpolicy, Discardoldestpolicy.
- AbortPolicy: Aborts the policy, which throws an rejectedexecution that the caller can catch to write direct processing code based on the actual need.
- Callerrunspolicy: The caller runs, the policy does not discard the task, nor throws an exception, but instead rolls some tasks back into the caller, reducing the traffic to the new task. Instead of executing a newly committed task in a thread in the pool, it executes the task in the thread that invoked execute, and when the thread pool's task queue is filled, the next task executes in the main thread when the Execute is invoked, due to the time it takes to perform the task, During this time, the main thread obviously cannot submit the task, thus ensuring that the thread pool processes the existing tasks during this time period.
- Discardpolicy: Discard the strategy and discard the task.
- Discardoldestpolicy: Discard the next task that will be executed, and then try to resubmit the new task (not applicable to the priority queue, as this will discard the highest priority waiting task)
Of course, we can use Semaphore (semaphore) to control the rate at which a task is committed.
Thread Factory
We can implement our own threads by customizing the thread factory. The specific examples are as follows:
Custom thread factory that records the name of the thread pool.
Importjava.util.concurrent.ThreadFactory;/*** Created by DB on 2017/9/1.*/ Public classMythreadfactoryImplementsThreadfactory {Private FinalString poolname; Publicmythreadfactory (String poolname) { This. poolname =poolname; } @Override PublicThread Newthread (Runnable r) {return NewMyappthread (r,poolname); }}
Custom thread class: Implements the name of the specified thread and sets the custom Uncaughtexecptionhandler.
ImportJava.util.concurrent.atomic.AtomicInteger;ImportJava.util.logging.Level;ImportJava.util.logging.Logger;/*** Created by DB on 2017/9/1.*/ Public classMyappthreadextendsThread { Public Static FinalString defalut_name = "Myappthread"; Private Static volatile BooleanDebuglifecycle =false; Private Static FinalAtomicinteger created =NewAtomicinteger (); Private Static FinalAtomicinteger Alive =NewAtomicinteger (); Private Static FinalLogger log =Logger.getanonymouslogger (); PublicMyappthread (Runnable r) { This(R,defalut_name); } PublicMyappthread (Runnable r,string name) {Super(R,name + "-" +created.incrementandget ()); Setuncaughtexceptionhandler (NewUncaughtexceptionhandler () {@Override Public voiduncaughtexception (Thread T, Throwable e) {log.log (Level.severe,"Uncaught in Thread" +T.getname (), E); } }); } Public voidrun () {Booleandebug =debuglifecycle; if(Debug) {Log.log (Level.fine,"Created" +getName ()); } Try{alive.incrementandget (); Super. Run (); }finally{alive.decrementandget (); if(Debug) {Log.log (Level.fine,"Exiting" +getName ()); } } } Public Static intgetthreadscreated () {returnCreated.get (); } Public Static intgetthreadsalive () {returnAlive.get (); } Public Static BooleanGetdebug () {returndebuglifecycle; } Public Static voidSetdebug (Boolean b) {debuglifecycle=b; }}
Extended Threadpoolexecutor
Threadpoolexecutor is extensible and provides several methods that can be rewritten in subclasses: BeforeExecute, AfterExecute, and terminated, which we can extend by implementing these methods.
The BeforeExecute and AfterExecute methods are called in the thread that executes the task, in which we can add logs, timings. The ability to monitor or collect statistical information. The AfterExecute is called regardless of whether the task returns normally from run or throws an exception. When BeforeExecute throws RuntimeException, the task will not be executed, and AfterExecute will of course not be called.
When the online pool completes the shutdown operation, it calls terminated, just after all the tasks have been completed and all worker threads are closed. In this approach we can implement the various resources allocated by executor during its life cycle, as well as perform operations such as sending notifications, logging, or collecting finalize statistics.
The specific framework is as follows:
ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit;/*** Created by DB on 2017/9/1.*/ Public classMythreadpoolexecutorextendsThreadpoolexecutor { PublicMythreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit, blockingqueue<runnable>workQueue) { Super(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, workQueue); } @Overrideprotected voidBeforeExecute (Thread T, Runnable R) {Super. BeforeExecute (t, R); } @Overrideprotected voidAfterExecute (Runnable R, Throwable t) {Super. AfterExecute (r, T); } @Overrideprotected voidterminated () {Super. terminated (); }}
Java Thread Cheng threadpoolexecutor