Thread Pool Benefits
In a business scenario, it is recommended that pooled objects be managed at this time if an object creation destruction overhead is relatively large.
For example, threads, JDBC connections, and so on, in high concurrency scenarios, if you can reuse previously destroyed objects, the system efficiency will be greatly improved.
Another benefit is that you can set the upper limit for pooled objects, such as preventing scenarios where the number of threads causing the system to crash is too high.
Thread pools in the JDK
The following are some of the main points to be explained below:
- Create a thread pool
- Submit a Task
- Potential downtime risks
- Thread Pool Size Configuration
- Custom Blocking Queue Blockingqueue
- Callback Interface
- Custom Deny Policy
- Custom Threadfactory
- Close the thread pool
Create a thread pool
We can create a series of thread pools by customizing the Threadpoolexecutor or the built-in executors of the JDK.
- Newfixedthreadpool: Creating a thread pool with a fixed number of threads
- Newsinglethreadexecutor: Creating a single-threaded pool
- Newcachedthreadpool: Create a thread pool that automatically expands the number of threads and automatically destroys it
- Newscheduledthreadpool: Creating a thread pool that supports scheduled tasks
Some of the above are implemented by new Threadpoolexecutor (), and the source code for the constructor is as follows:
1/** 2 * @param the number of core threads in the Corepoolsize pool, the number of threads going into the blocking queue 3 * @param maximumpoolsize Maximum number of threads to create 4 * @param KeepAliveTime Thread Survival Time 5 * @param unit survival time in units 6 * @param workQueue thread overflow after blocking queue 7 */8 public Threadpoolex Ecutor (int corepoolsize, 9 int maximumpoolsize,10 long Keepali vetime,11 timeunit unit,12 blockingqueue<runnable> WORKQ Ueue) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthreadfactory (), DE Faulthandler);}15 public static ExecutorserviceNewfixedthreadpool(int nthreads) {Threadpoolexecutor to New nthreads, Nthreads, 0L, Timeunit.milliseconds, new Linkedblockingqueue<runnab Le> ());}19 public static ExecutorserviceNewsinglethreadexecutor() {return new Executors.finalizabledelegatedexecutorservice22 (new Threadpoolexecutor (1, 1, 0L , Timeunit.milliseconds, New linkedblockingqueue<runnable> ());}24 public static ExecutorserviceNewcachedthreadpool() {threadpoolexecutor (0, Integer.max_value, 60L, Timeunit.seconds, new synchronousqueue<runnable > ());}28 public static ScheduledexecutorserviceNewscheduledthreadpool(int corepoolsize) {Scheduledthreadpoolexecutor (corepoolsize),}32 public scheduledthreadpoolexecutor (int Corepoolsize) {corepoolsize, integer.max_value, 0, Timeunit.nanoseconds, new Scheduledthreadpoolexecutor. Delayedworkqueue ()); 35}
Submit a Task
Call Executorservice.execute (runnable) or submit (runnable) directly,
The difference between execute and submit is that the submit will return to the future to get any execution results.
Let's take a look at the usage examples of newscheduledthreadpool.
1 public class Schedulepooldemo {2 3 public static void Main (string[] args) {4 Scheduledexecutorservice serv Ice = Executors.newscheduledthreadpool (10); 5 //If the previous task is not completed, the schedule will not start 6 service.scheduleatfixedrate (new Runnable () {7 @Override 8 public void Run ( {9 try { thread.sleep (+); one//every two seconds printing. System.out.println (System.currenttimemillis () /1000); catch (Interruptedexception e) { e.printstacktrace (); }16 }17 }, 0, 2, timeunit.seconds); }19}
Potential downtime risks
Use executors to create a risk of potential downtime. The disadvantages of its returned thread pool object are as follows:
- Fixedthreadpool and Singlethreadpoolpool: the allowable request Queue length is integer.max_value, which can accumulate a large number of requests, resulting in OOM.
- Cachedthreadpool and Scheduledthreadpool: The number of created threads allowed is integer.max_value, which may create a large number of threads, resulting in OOM.
In summary, in a thread pool scenario where there may be a large number of requests, a custom threadpoolexecutor is recommended to create the thread pool, as specified in the constructor configuration.
Thread Pool Size Configuration
Typically differentiated by task type, assuming that the CPU is N-core
- CPU-intensive tasks need to reduce the number of threads, reduce the overhead of switching between threads, and configure the thread pool size to be n + 1.
- IO-intensive tasks can increase the number of threads and configure the thread pool size to be N * 2.
- Hybrid tasks can be split into CPU-intensive and IO-intensive, standalone configurations.
Custom Blocking Queue Blockingqueue
The main store is waiting for the execution of the thread, Threadpoolexecutor in support of customizing the queue to implement different queued queues.
- Arrayblockingqueue: FIFO queue, created with a specified size, bounded;
- Linkedblockingqueue: The first-out queue implemented using the list, the default size is Integer.max_value;
- Synchronousqueue: does not save the submitted task, the data will not be cached in the queue for the producers and consumers to each other, and leave together.
- Priorityblockingqueue: Priority-enabled queues
Callback Interface
The thread pool provides some callback methods, as shown below.
1 executorservice service = new Threadpoolexecutor (5, 5, 0L, Timeunit.milliseconds, new linkedblockingdeque< Runnable> ()) {2 3 @Override 4 protected void BeforeExecute (Thread T, Runnable R) {5 System.out.println ("Ready to perform task:" + r.tostring ()); 6 } 7 8 @Override 9 protected void AfterExecute (Runnable R, Throwable t) {Ten System.out.println (" End Task: "+ r.tostring ()); }12 @Override14 protected void terminated () { System.out.println ( "Thread pool Exit"); }17 };
The status of the thread pool can be monitored in the callback interface, such as the maximum time to execute a task, the average time, the shortest time, and so on, as well as some other attributes:
- Taskcount: The number of tasks that the thread pool needs to perform.
- Completedtaskcount: The number of tasks that the thread pool has completed during the run. Less than or equal to Taskcount.
- Largestpoolsize: The maximum number of threads that the thread pool has ever created. This data lets you know if the thread pool is full. As equals to the maximum size of the thread pool, the thread pool was once full.
- Getpoolsize: The number of threads in the thread pool. If the thread pool is not destroyed, the threads in the pool are not automatically destroyed, so this size only increases.
- Getactivecount: Gets the number of active threads.
Custom Deny Policy
After the thread pool is running full load, it may be necessary to reject the execution of some of the tasks because of the time space problem.
The JDK provides a rejectedexecutionhandler interface, and several thread-reject policies are built in
- AbortPolicy: A direct deny policy, throws an exception.
- Callerrunspolicy: The caller executes the task policy by itself.
- Discardoldestpolicy: Discards the oldest non-executing task policy.
The use of the method is also very simple, directly to the ThreadPool
1 executorservice service = new Threadpoolexecutor (5, 5, 0L, Timeunit.milliseconds, 2 new synchronousqueue< Runnable> (), 3 executors.defaultthreadfactory (), 4 new Rejectedexecutionhandler () {5 @Override6 Public void Rejectedexecution (Runnable R, Threadpoolexecutor executor) {7 System.out.println ("Reject task:" + R.tostring ()); 8 }9 });
Custom Threadfactory
The thread factory is used to create threads in the pool. For example, in the factory all give thread Setdaemon (true), so that when the program exits, the thread exits automatically.
or uniformly specify thread priority, set name, and so on.
1 class Namedthreadfactory implements Threadfactory {2 private static final Atomicinteger Threadindex = new Atomicint Eger (0); 3 private Final String baseName; 4 private Final Boolean daemon; 5 6 Public namedthreadfactory (string BaseName) {7 This (BaseName, True); 8 } 9 public namedthreadfactory (String baseName, Boolean daemon) {11
this.basename = basename;12 This.daemon = daemon;13 }14 public Thread newthread (Runnable Runnable) { Thread thread = new Thread (runnable, This.basename + "-" + threadindex.getandincrement ()); Thread.setdaemon (This.daemon); return thread;19 }20}
Close the thread pool
Unlike the direct new thread, the thread pool for local variables needs to be shut down manually, or it can cause a threading leak.
The default provides two ways to turn off the thread pool.
- Shutdown: All tasks, including the blocking queue, will not terminate until they are executed, but will not accept new tasks.
- Shutdownnow: Terminates the thread pool immediately, interrupts the task being performed, and empties the queue.
original link : https://www.cnblogs.com/xdecode/p/9119794.html
Java high concurrency thread pool detailed