Threadpoolexecutor mechanism
I. Overview
1, Threadpoolexecutor as the Java.util.concurrent package to provide the basis for external implementation, in the form of internal thread pool to provide management task execution, thread scheduling, thread pool management and other services;
2. The threading service provided by the Executors method is implemented by parameter setting to implement different thread pool mechanism.
3, first to understand its thread pool management mechanism, to help correct use, to avoid bad use caused serious failure. At the same time can be based on their own needs to implement their own thread pool
Ii. Explanation of the core construction method
The following is the most core construction method of Threadpoolexecutor
PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, timeunit unit, Blockingqueue<Runnable>WorkQueue, Threadfactory threadfactory, Rejectedexecutionha Ndler handler) {if(Corepoolsize < 0 | |maximumpoolsize<= 0 | |maximumpoolsize< Corepoolsize | |KeepAliveTime< 0) Throw Newillegalargumentexception (); if(WorkQueue = =NULL|| Threadfactory = =NULL|| Handler = =NULL) Throw NewNullPointerException (); This. corepoolsize =corepoolsize; This. maximumpoolsize =maximumpoolsize; This. WorkQueue =WorkQueue; This. KeepAliveTime =Unit.tonanos (KeepAliveTime); This. Threadfactory =threadfactory; This. Handler =handler; }
explanation of construction method parameters
parameter name |
role |
corepoolsize |
core thread pool Size |
maximumpoolsize |
maximum thread pool size |
keepalivetime |
thread pool The maximum surviving time of idle threads in excess of corepoolsize number, allowcorethreadtimeout (true) to make the core thread valid for |
timeunit |
Keep Alivetime Time Unit |
workQueue |
block task queue |
threadfactory |
new thread Factory |
rejectedexecutionhandler |
When the number of submitted tasks exceeds the sum of Maxmumpoolsize+workqueue, the task is assigned to Rejectede Xecutionhandler to handle |
Highlights:
One of the things that's easy to misunderstand is the relationship between Corepoolsize,maximumpoolsize,workqueue.
1. When the thread pool is smaller than corepoolsize, the new commit task creates a new thread to perform the task, even if there are idle threads in the thread pools at this time.
2. When the thread pool reaches corepoolsize, the new commit task is put into Workqueue, waiting for the task schedule in the thread pool to execute
3. When Workqueue is full and maximumpoolsize> Corepoolsize, the new commit task creates a new thread to perform the task
4. When the number of submitted tasks exceeds maximumpoolsize, the new submission task is handled by Rejectedexecutionhandler
5. When the thread pool exceeds the corepoolsize thread and the idle time reaches KeepAliveTime, the idle thread is closed;
6. When you set Allowcorethreadtimeout (true), Thread pool corepoolsize thread idle time reaches KeepAliveTime will also close
thread management mechanism diagram:
Third, Executors provides a thread pool configuration scheme
1, constructs a thread pool with a fixed number of threads, and configures Corepoolsize to be the same size as maximumpoolsize. At the same time, an unbounded linkedblockingqueue is used to hold the blocking task, so the redundant tasks will exist to block the queue and will not be processed by Rejectedexecutionhandler
Public Static Executorservice newfixedthreadpool (int nthreads) { returnnew Threadpoolexecutor (Nthreads, nthreads, 0L, timeunit.milliseconds, new Linkedblockingqueue<runnable>()); }
2. Construct a buffer function thread pool, configure corepoolsize=0,maximumpoolsize=integer.max_value,keepalivetime=60s, and a non-capacity blocking queue Synchronousqueue, so a new thread execution will be created after the task is committed, and the thread will be idle for more than 60s to destroy
Public Static Executorservice Newcachedthreadpool () { returnnew threadpoolexecutor (0, Integer.max_value, 60L, timeunit.seconds, new synchronousqueue<runnable> ()); }
3. Construct a thread pool that supports only one threads, configure corepoolsize=maximumpoolsize=1, and unbounded blocking queue linkedblockingqueue; Ensure that tasks are executed serially by one thread
Public Static Executorservice Newsinglethreadexecutor () { returnnew Finalizabledelegatedexecutorservice (new threadpoolexecutor (1, 1, 0L, Timeunit.milliseconds, new linkedblockingqueue<runnable>())); }
4. Construct a thread pool with timed function, configure corepoolsize, and unbounded delay block queue delayedworkqueue; Interestingly: Maximumpoolsize=integer.max_value, Since Delayedworkqueue is an unbounded queue, this value is meaningless
Public StaticScheduledexecutorservice Newscheduledthreadpool (intcorepoolsize) { return NewScheduledthreadpoolexecutor (corepoolsize); } Public StaticScheduledexecutorservice Newscheduledthreadpool (intcorepoolsize, Threadfactory threadfactory) { return NewScheduledthreadpoolexecutor (corepoolsize, threadfactory); } PublicScheduledthreadpoolexecutor (intcorepoolsize, Threadfactory threadfactory) { Super(Corepoolsize, Integer.max_value, 0, Timeunit.nanoseconds,Newdelayedworkqueue (), threadfactory); }
Iv. Customizing the thread pool that belongs to you
ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.RejectedExecutionHandler;Importjava.util.concurrent.ThreadFactory;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.atomic.AtomicInteger; Public classCustomthreadpoolexecutor {PrivateThreadpoolexecutor pool =NULL; /*** Thread Pool initialization method * * Corepoolsize core thread pool size----* maximumpoolsize maximum thread pool size----* KeepAliveTime more than Corepoolsize Number of idle threads maximum survival time----timeunit * timeunit keepalivetime Time Unit----timeunit.minutes * workQueue block queue----NE W arrayblockingqueue<runnable> (10) ====10 capacity blocking queue * Threadfactory new Thread factory----New customthreadfactory () = = Custom Thread Factory * Rejectedexecutionhandler when the number of submitted tasks exceeds Maxmumpoolsize+workqueue, * that is, when a 41st task is submitted ( The previous thread is not finished, this test method uses sleep (100)), * The task is given to Rejectedexecutionhandler to handle*/ Public voidinit () {Pool=NewThreadpoolexecutor (10, 30, 30, Timeunit.minutes,NewArrayblockingqueue<runnable> (10), Newcustomthreadfactory (),NewCustomrejectedexecutionhandler ()); } Public voiddestory () {if(Pool! =NULL) {Pool.shutdownnow (); } } PublicExecutorservice Getcustomthreadpoolexecutor () {return This. Pool; } Private classCustomthreadfactoryImplementsThreadfactory {PrivateAtomicinteger count =NewAtomicinteger (0); @Override Publicthread Newthread (Runnable r) {thread T=NewThread (R); String ThreadName= Customthreadpoolexecutor.class. Getsimplename () + count.addandget (1); System.out.println (ThreadName); T.setname (ThreadName); returnT; } } Private classCustomrejectedexecutionhandlerImplementsRejectedexecutionhandler {@Override Public voidRejectedexecution (Runnable R, Threadpoolexecutor executor) {//Log Exceptions//alarm processing, etc.SYSTEM.OUT.PRINTLN ("Error ......")); } } //test the constructed thread pool Public Static voidMain (string[] args) {customthreadpoolexecutor exec=NewCustomthreadpoolexecutor (); //1. InitializeExec.init (); Executorservice Pool=Exec.getcustomthreadpoolexecutor (); for(intI=1; i<100; i++) {System.out.println ("Submit a" + i + "Quests!"); Pool.execute (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (300); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("running====="); } }); } //2. Destruction----cannot be destroyed here because the task is not completed and the task cannot be executed if the thread pool is destroyed//exec.destory (); Try{Thread.Sleep (10000); } Catch(interruptedexception e) {e.printstacktrace (); } }}
The method establishes a core thread number of 30, the buffer queue has 10 thread pools. Each thread task, the execution will sleep 0.1 seconds first, guaranteed to submit 40 tasks when no task is executed, so submit a 41st task is, will be handed over to the Customrejectedexecutionhandler class to handle.
http://825635381.iteye.com/blog/2184680
Java Advanced----threadpoolexecutor mechanism (RPM)