Java thread pool in-depth understanding

Source: Internet
Author: User

Recent projects in the performance of the Alarm module optimization, many places using the thread pool technology, summarized as follows.

Package Com.coshaho.threadpool;import Java.util.concurrent.blockingqueue;import java.util.concurrent.Executors; Import Java.util.concurrent.rejectedexecutionhandler;import Java.util.concurrent.threadfactory;import Java.util.concurrent.threadpoolexecutor;import java.util.concurrent.timeunit;/** * thread pool learning * @author Coshaho */public Class Mythreadpool {/** * First thread pool initialization *///core threads number private int corepoolsize;//maximum number of threads private int maximumpoolsize;//idle thread Survival time Private long keepalivetime;//idle thread survival time Unit private Timeunit unit;//thread blocking queue private blockingqueue<runnable> WorkQueue  ;/** * Thread Creation factory, general custom, used to encapsulate runnable tasks for incoming ThreadPool * default: Executors.defaultthreadfactory () * Public interface Threadfactory  {* Thread newthread (Runnable R); *} */private threadfactory threadfactory;//thread rejection mechanism private rejectedexecutionhandler handler;public void Initthreadpoolexecutor () {Threadpoolexecutor executor = new Threadpoolexecutor (corepoolsize, Maximumpoolsize, KeepAliveTime, Unit,workqueue,threadfactory,handler);Set thread pool core thread number executor.setcorepoolsize (corepoolsize);//set thread pool maximum thread Count executor.setmaximumpoolsize (maximumpoolsize);// Initializes a core thread executor.prestartcorethread ();//initializes all core threads executor.prestartallcorethreads ();//does not immediately terminate the thread pool, Instead, wait until all tasks in the cache queue have been executed before terminating, but will no longer accept new tasks Executor.shutdown ();//terminate the thread pool immediately, try to interrupt the task that is being performed, and empty the task cache queue. Returns the task Executor.shutdownnow () that has not been performed; /** * Chapter II thread pool task processing mechanism * A task after the processing mechanism * 1, when the number of thread pool threads less than corepoolsize, immediately create a new thread to perform the task; * 2, when the number of thread pool threads equals corepoolsize,workqueue dissatisfaction, the task Into the Workqueue queue, waiting for dispatch; * 3, when the Workqueue is full, the number of thread pool threads is less than maximumpoolsize, the new thread executes the task; * 4, when the number of thread pool threads equals Maximumpoolsize,workqueue full, The thread rejection mechanism is used to process the task. *//** * Chapter III Thread blocking queue * Workqueue type is BLOCKINGQUEUE&LT;RUNNABLE&GT, usually the following three types are available: * 1, Arrayblockingqueue: array-based FIFO Queue, this queue must be created when the size is specified; * 2, Linkedblockingqueue: List-based FIFO queue, if this queue size is not specified when created, the default is Integer.max_value; * 3, synchronous Queues: This queue is special, it does not save the submitted task, but instead creates a new thread directly to perform the newly-arrived task. *//** * Fourth thread reject mechanism */public void Rejectedexecutionhandlerlearn () {//Drop task and throw rejectedexecutionexception Exception handler = new THR eadPoolexecutor.abortpolicy ();//discards the task, but does not throw an exception handler = new Threadpoolexecutor.discardpolicy ();//discards the task at the front of the queue, Then retry the task (repeat this process) handler = new Threadpoolexecutor.discardoldestpolicy ();//The task is handled by the calling thread handler = new Threadpoolexecutor.callerrunspolicy ();} /** * Fifth JDK default thread pool */public void Jdkthreadpool () {//Create a buffer pool with buffer pool capacity size of Integer.MAX_VALUEExecutors.newCachedThreadPool ();    Create a buffer pool with a capacity of 1 executors.newsinglethreadexecutor ();//Create a fixed-size buffer pool Executors.newfixedthreadpool (5);                                  }/**public static executorservice newfixedthreadpool (int nthreads) {return new Threadpoolexecutor (Nthreads, NThreads, 0L, Timeunit.milliseconds, new Linkedblockingqueue<ru Nnable> ());} public static Executorservice Newsinglethreadexecutor () {return new Finalizabledelegatedexecutorservice (new Th Readpoolexecutor (1, 1, 0L, timeunit.milliseconds, new Linked Blockingqueue<runnable> ()));}                                  public static Executorservice Newcachedthreadpool () {return new Threadpoolexecutor (0, Integer.max_value, 60L, Timeunit.seconds, New synchronousqueue<runnable> ());} *//** * Sixth thread pool Size setting * 1, if the CPU-intensive task, you need to squeeze the CPU as much as possible, the reference value can be set to ncpu+1; * 2, if it is an IO-intensive task, the reference value can be set to 2*NCPU.     *//** * Seventh JDK Source * Creates a new {@code Threadpoolexecutor} with the given initial * parameters. * * @param corepoolsize the number of threads to keep in the pool, even * if they is idle, unless {@code a      Llowcorethreadtimeout} is set * @param maximumpoolsize the maximum number of threads to allow in the * pool * @param KeepAliveTime when the number of threads was greater than * the core, this is the maximum time tha     T excess idle threads * 'll wait for new tasks before terminating. * @param unit The time unit for the {@code keepalivetime} argument * @param workQueue theQueue to use for holding tasks before they is * executed.     This queue would hold only the {@code Runnable} * Tasks submitted by the {@code Execute} method. * @param threadfactory the factory to use when the executor * creates a new thread * @param handler the Han Dler to use when execution was blocked * because the thread bounds and queue capacities are reached * @throw     S illegalargumentexception if one of the following holds:<br> * {@code corepoolsize < 0}<br> * {@code KeepAliveTime < 0}<br> * {@code maximumpoolsize <= 0}<br> * { @code Maximumpoolsize < corepoolsize} * @throws nullpointerexception if {@code WorkQueue} * or {@code t                               Hreadfactory} or {@code handler} is a null public threadpoolexecutor (int corepoolsize,              int maximumpoolsize, Long keepalivetime,                 Timeunit unit, blockingqueue<runnable> WorkQueue, Threadfactory threadfactory, Rejectedexecutionhandler handler) */}

Java thread pool in-depth understanding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.