Java Threading Series Java thread pool details

Source: Internet
Author: User

The concept of a first-thread pool and why it needs a thread pool:

We know that when we create a thread ourselves, if that thread goes into a dead state when it finishes the task, so that if we need to recreate a thread when we use one thread at a time, the thread is created at a cost, if we need to use threads frequently in our programs, and each thread executes a short time , shorter than the time it takes to create and destroy threads is much more costly, as is often the case in server applications where a single task is processed for a short time and the number of requests is huge. Obviously if the frequent creation of the destruction thread efficiency will be very low.

So can we make a thread reusable, that is, when a thread finishes executing and does not destroy the thread, but instead waits for other tasks to be performed. The answer is to use the thread pool.

What is thread pool: The basic idea of pool thread pool is a kind of object pooling idea, which opens up a memory space, which contains many (not dead) threads, and the pool thread execution schedule is handled by the pool manager. When a thread task is taken from a pool, the threads object is pooled after execution, which avoids the performance overhead of repeatedly creating thread objects and saves system resources.


The benefits of using thread Cheng reasonably for the use of threads alone are as follows:

1 Reduce resource consumption because the thread pool reduces the number of threads created and destroyed, and each worker thread can be reused to perform multiple tasks.

2 Improve response speed. Because threads in a thread pool are created by the thread pool manager, the task can be executed without waiting for the thread to be created when the task arrives.

3 Increase the manageability of threads, the thread pool provides a solution for threading life-cycle overhead problems and resource shortages, and threads can be uniformly distributed, tuned, and monitored using the thread pool.


Two core classes about the Java thread pool

When it comes to thread pooling, first we need to know three classes: Executors, Executorservice and Threadpoolexecutor. Where executors is equivalent to a tool class that creates a thread pool, and Executorservice is the real thread pool interface, and Threadpoolexecutor is the concrete implementation class of Executorservice. Let's introduce one by one:

1Executors: Create a tool class for the thread pool, where many static methods are available to create a thread pool, and the important methods in this class are as follows:

public static Executorservice newfixedthreadpool (int nthreads) {return new Threadpoolexecutor (Nthreads, Nthreads, 0L, Timeunit.milliseconds, new Linkedblockingque    Ue<runnable> ());            } public static Executorservice Newsinglethreadexecutor () {return new Finalizabledelegatedexecutorservice                                    (New Threadpoolexecutor (1, 1, 0L, Timeunit.milliseconds,    New Linkedblockingqueue<runnable> ()));                                      }public static Executorservice Newcachedthreadpool () {return new Threadpoolexecutor (0, Integer.max_value, 60L, Timeunit.seconds, new synchronousqueue<runnable&    gt; ()); }public static scheduledexecutorservice newscheduledthreadpool (int corepoolsize) {return new Scheduledthreadpoolex    Ecutor (corepoolsize); }
Let's look at it one by one:

1 public static Executorservice newfixedthreadpool (int nthreads)

Creates a fixed-size thread pool by passing in an int type integer (creates a thread pool that reuses a fixed number of threads), creating a thread each time a task is committed, Threads that are committed after the thread reaches the maximum size of the thread pool wait in the queue.


2 public static Executorservice Newsinglethreadexecutor ()

Create a single thread pool (creates an Executor, that uses a, thread).


3 public static Executorservice Newcachedthreadpool ()

Create a thread pool that can be cached, with the idea of creating a new thread when the wireless path is idle, or reusing the previously created thread when the previously created thread is idle (creates a thread pool that creates new threads as needed, but Wil L Reuse previously constructed threads when they is available.)


4 public static Scheduledexecutorservice newscheduledthreadpool (int corepoolsize)

Create a thread pool that can be executed on a timed or periodic basis (creates a thread pool that can schedule commands to run after a given delay, or to execute periodical Ly.)


2ExecutorService: You can see that the return values of several important methods in the executors described above are executorservice, so let's take a look at the definition of its class:

Public interface Executorservice extends Executor {void shutdown ();  List<runnable> Shutdownnow ();  Boolean IsShutDown ();  Boolean isterminated ();  Boolean awaittermination (long timeout, timeunit unit) throws Interruptedexception;  <T> future<t> Submit (callable<t> Task);  <T> future<t> Submit (Runnable task, T result);  Future<?> Submit (Runnable Task); <T> list<future<t>> InvokeAll (collection<? extends callable<t>> tasks) throws Interru  Ptedexception;                                  <T> list<future<t>> InvokeAll (collection<? extends callable<t>> tasks,  Long timeout, timeunit unit) throws Interruptedexception; <T> T invokeany (collection<? extends callable<t>> tasks) throws Interruptedexception, Executionex  ception;   <T> T invokeany (collection<? extends callable<t>> tasks, long timeout, timeunit unit)      Throws Interruptedexception, Executionexception, TimeoutException;} 

You can see that Executorservice is an interface that inherits from executor (note that this is not the executors described above), so let's take a look at the definition of the executor interface:

Public interface Executor {   void execute (Runnable command);}
You can see that the executor interface code is simple enough to contain only a void execute (Runnable command); This means that the Executorservice interface inherits from the executor interface, and then adds some of its own methods on top of it.


3ThreadPoolExecutor class: This is the core class to create a thread, and the focus of our explanation, first we look at the definition of its class:

Can see Threadpoolexecutorclass inherits from Abstractexecutorservice,So let's take a look at the definition of the Abstractexecutorservice class:

Public abstract class Abstractexecutorservice implements Executorservice
Can see the Abstractexecutorservice class is an abstract class, it implements the Executorservice, as for the Abstractexecutorservice class content, more I do not post out, interested can go to look at the source code, The reader only needs to know the Abstractexecutorservice class it implements most of the methods in the Executorservice interface, and some methods are not implemented so it is an abstract class.

Next, look at the constructors in the Threadpoolexecutor class.

 Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, BLOCKINGQUEUE&LT;RUNNABLE&G T WorkQueue) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthrea    Dfactory (), DefaultHandler);                              } public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, blockingqueue<runnable& Gt WorkQueue, Threadfactory threadfactory) {This (corepoolsize, Maximumpoolsize, Keepaliv    ETime, Unit, WorkQueue, Threadfactory, DefaultHandler);                              }public threadpoolexecutor (int corepoolsize, int maximumpoolsize,               Long KeepAliveTime,               Timeunit unit, blockingqueue<runnable> WorkQueue,             Rejectedexecutionhandler handler) {This (corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,    Executors.defaultthreadfactory (), handler);                              } public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, blockingqueue<runnable& Gt  WorkQueue, Threadfactory threadfactory, Rejectedexecutionhandler            Handler) {if (Corepoolsize < 0 | |            Maximumpoolsize <= 0 | |            Maximumpoolsize < Corepoolsize | |        KeepAliveTime < 0) throw new IllegalArgumentException (); if (WorkQueue = = NULL | | threadfactory = = NULL | | handler = NULL) throw new NullPointerException ();        This.corepoolsize = corepoolsize;        This.maximumpoolsize = maximumpoolsize;        This.workqueue = WorkQueue;        This.keepalivetime = Unit.tonanos (KeepAliveTime);        This.threadfactory = threadfactory;    This.handler = handler; }

You can see that the Threadpoolexecutor class provides us with four constructors, fourth of which is the most basic constructor, and the remaining three constructors call the fourth constructor within their methods. So we focus on the meaning of the parameters of the fourth constructor:

1 int corepoolsize: The size of the kernel pool, is an int type parameter,

2 int maximumpoolsize: The maximum number of threads for the thread pool, which is an int parameter that represents the maximum number of threads that can be created in the thread pools (the maximum numbers of threads to enable in the pool)

3 Long KeepAliveTime: Indicates the maximum length of time a thread will be terminated when no task is executed, which is a long parameter (this is the maximum-excess idle threads will-wait for new Tasks before terminating. KeepAliveTime only works if the number of threads in the thread pool is greater than corepoolsize (when the numbers of threads is greater than the C ore), until the number of threads in the thread pool is not greater than corepoolsize, that is, if a thread is idle for KeepAliveTime when the number of threads in the thread pool is greater than corepoolsize, then it terminates. Until the number of threads in the thread pool does not exceed corepoolsize.


4 Timeunit Unit: The time unit of the parameter KeepAliveTime (the period of unit for the {@code KeepAliveTime} argument)

5 blockingqueue<runnable> workQueue: Block queue, which is used to store tasks waiting to be executed (the queue to using for holding tasks before they is executed), which  Queue only accommodates the tasks of the Runnable interface submitted through the Execute method (the queue to uses for holding tasks before they is executed. This queue would hold only the {@code Runnable} tasks submitted by the {@code Execute} method.)

6 threadfactory threadfactory: Thread factory, primarily used to create threads (the factory to using when the executor creates a new thread)

7 Rejectedexecutionhandler Handler: It means that when a thread's execution is blocked because it reaches the field boundary and the queue capacity reaches the extreme value (to the if execution is blocked because the thread Bounds and queue capacities is reached) and the policy that should be taken when the task (rejectedexecution) is rejected. Its value is a Rejectedexecutionhandler interface, which takes four cases:

Threadpoolexecutor.abortpolicy: Discards the task and throws a rejectedexecutionexception exception.
Threadpoolexecutor.discardpolicy: Also discards the task, but does not throw an exception.
Threadpoolexecutor.discardoldestpolicy: Discards the first task in the queue and then tries to perform the task again (repeat this process)
Threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread

The above four classes are threadpoolexecutor static inner classes, they all implement the Rejectedexecutionhandler interface, its class is defined as follows:


Next look at the important methods of the Threadpoolexecutor class:

public void Execute (Runnable command) publicly void shutdown () public list<runnable> Shutdownnow () Submit ()

As we described above, the executor interface contains only a void execute (Runnable command), the declaration of the method, the Executorservice interface inherits from the executor interface, and then adds some of its own methods on that basis. While the Abstractexecutorservice class implements most of the methods in the Executorservice interface, a few methods are not implemented (so it is an abstract class), while the above methods execute (), Shutdown (), Shutdownnow () are not implemented in the Abstractexecutorservice class, they are Threadpoolexecutorclass, and submit is implemented in the Abstractexecutorservice class.

Note that the Execute () method is actually a method declared in executor, which is implemented in Threadpoolexecutor, which is the core method of Threadpoolexecutor, which can be used to submit a task to the thread pool. To the thread pool to execute.


Use of three Java thread pools:

Instead of using the Threadpoolexecutor core class, we use a few static methods in the Executors tool class when using the thread pool.

Executors.newcachedthreadpool ();            Create a buffer pool with buffer pool capacity of Integer.MAX_VALUEExecutors.newSingleThreadExecutor ();       Create a buffer pool executors.newfixedthreadpool (int) with a capacity of 1;          Create a fixed-size thread pool executors.newscheduledthreadpool (int)      //Create a timed execution thread pool

The use of these methods is similar, so we create a fixed-size thread pool executors.newfixedthreadpool (int); This method is an example of how the thread pool is used. I intend to use the server-side use of the wire pool connection client socket request communication as an example to explain its usage, the code is as follows:

public class Server {private Executorservice executorservice;//thread pool private ServerSocket ServerSocket = Null;private Socke T socket = null;private Boolean isstarted = True;public Server () {try {//create thread pool, pool has (number of CPUs *50) thread executorservice = Executo Rs.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () *; serversocket = new ServerSocket ( Constants.server_port);} catch (IOException e) {e.printstacktrace (); Quit ();}} public void Start () {System.out.println (MYDATE.GETDATECN () + "server started ..."); try {while (isstarted) {// The server-side accept operation is placed in a while loop to continuously monitor the client's connection request socket = serversocket.accept (); String IP = socket.getinetaddress (). toString (); System.out.println (MYDATE.GETDATECN () + "User:" + IP + "Connected");//To support multiuser concurrent access, use thread pooling to manage each user's connection request//request for each user to be placed in a single thread to execute if (socket.isconnected ()) Executorservice.execute (new Sockettask (socket));//Add to Thread pool}if (socket! = NULL) socket.close (); if (serversocket! = null) Serversocket.close ();} catch (IOException e) {e.printstacktrace ();//isstarted = false;}} PrivateFinal class Sockettask implements Runnable {private socket socket = null;private Inputthread in;private outputthread out;p Rivate outputthreadmap map;public sockettask (socket socket) {This.socket = Socket;map = Outputthreadmap.getinstance ();} @Overridepublic void Run () {out = new Outputthread (socket, map);////first instantiates the write message thread (writes the corresponding user's write thread to the map buffer) in = new Inputthread (s Ocket, out, map);//re-instantiate the read message thread Out.setstart (true); In.setstart (true); In.start (); Out.start ();}} /** * quit */public void quit () {try {this.isstarted = False;serversocket.close ();} catch (IOException e) {E.printstacktrace ();}} public static void Main (string[] args) {new Server (). Start ();}}
As you can see from the preceding code example, the thread pool uses the following steps:

1 Use executors a few static methods in this tool class to create a Threadpoolexecutor object, such as

Executorservice = Executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () * 50);//create thread pool with (number of CPUs *50) Bar Thread
Note that several static methods return the Executorservice interface of their parent class, usually we do not specify the number of threads directly as a fixed value, but instead use a similar Runtime.getRuntime.availableProcessors () * 50 ways to take full advantage of the performance of multi-core computers,


2 Create a thread that implements the Runnable interface, such as:

Private Final class Sockettask implements Runnable

Rewrite its run method to complete its own business logic in the Run method.


3 Call the Execute () method of the Executorservice object to execute the Runnable object created in 2, the parameter of the method is a Runnable object, such as:

Executorservice.execute (new Sockettask (socket));//Add to thread pool

Note that the Execute () method is actually a method declared in executor, and is implemented specifically in Threadpoolexecutor.


Ok above is I understand the content of Java thread pool, crossing if feel good, please remember to click on the bottom of the "top" or praise give me a little encouragement Oh!



















Java Threading Series Java thread pool details

Related Article

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.