The thread pool in Java

Source: Internet
Author: User

1. Benefits of using the thread pool

A, reduce resource consumption . Reduce the consumption caused by thread creation and destruction by reusing created threads;

b, improve the response speed . When the task arrives, the task can be executed without waiting for the thread to be created;

C, improve the manageability of threads. Threads are scarce resources that, if created indefinitely, not only consume system resources, but also reduce system stability, use line thread, and unify distribution, tuning, and monitoring.

2. The implementation principle of thread pool

When the thread pool wants to submit a task, the main processing flow of the thread pool

The source code for the Execute () method in jdk1.8 Threadpoolexecutor is as follows:

1  Public voidExecute (Runnable command) {2         if(Command = =NULL)3             Throw Newnullpointerexception ();4         intc =ctl.get ();//atomic type Atomicinteger ctl, get value5         if(Workercountof (c) <corepoolsize) {//Determine if the current worker thread is less than the number of core threads6             if(Addworker (Command,true) //is the creation of a new worker thread, and the current task is passed in to process and return the result,corepoolsize 7                 return;8c =ctl.get ();//If it fails, continue to execute the following code to determine9         }Ten         if(IsRunning (c) &&workqueue.offer (command)) { One             intRecheck =ctl.get (); A             if(! isrunning (Recheck) &&Remove (command)) - reject (command); -             Else if(Workercountof (recheck) = = 0) theAddworker (NULL,false);//Join a worker thread -         } -         Else if(!addworker (Command,false) //Create a new thread,maximumpoolsize  - reject (command); +}

Note the second parameter of Addwork core: core? corepoolsize:maximumpoolsize

1 Private BooleanAddworker (Runnable Firsttask,BooleanCore) {2 Retry:3          for (;;) {4             intc =ctl.get ();5             intrs =runstateof (c);6 7             //Check If queue empty only if necessary.8             if(Rs >= SHUTDOWN &&9! (rs = = SHUTDOWN &&TenFirsttask = =NULL&& One!Workqueue.isempty ())) A                 return false; -  -              for (;;) { the                 intWC =Workercountof (c); -                 if(WC >= Capacity | | -WC >= (core?corepoolsize:maximumpoolsize)) -                     return false; +                 if(Compareandincrementworkercount (c)) -                      Breakretry; +c = Ctl.get ();//Re-read CTL A                 if(Runstateof (c)! =rs) at                     Continueretry; -                 //Else CAS failed due to workercount change; retry Inner Loop -             } -}

Thread execution tasks in a thread pool are divided into two situations:

A, when creating a thread in the Execute () method, the thread is allowed to perform the current task;

b, after this thread has performed the above tasks, it will be repeatedly fetched from the Blockingqueue task to execute.

3, the use of thread pool

We can create a thread pool through threadpoolexecutor.

New Threadpoolexecutor (int corepoolsize,
int Maximumpoolsize,
Long KeepAliveTime,
Timeunit Unit,
Blockingqueue<runnable> WorkQueue,
Threadfactory Threadfactory,
Rejectedexecutionhandler handler);

corepoolsize: The base size of the thread pool , when a task is submitted to the thread pool, the line pool creates a thread to perform the task, even if other idle basic threads are able to perform new tasks , Wait until the number of tasks that need to be executed is greater than the thread pool base size. If you call the Prestartallcorethreads () method of the thread pool, the thread pool creates and starts all the basic threads in advance.

maximumpoolsize: Maximum number of thread pools, the maximum number of threads that the thread pool is allowed to create. If the queue is full and the number of threads that have been created is less than the maximum number of threads, the thread pool will then create new threads to perform the task. It is worth noting that if you use the unbounded task queue This parameter has little effect.

KeepAliveTime: Thread activity hold time , when worker threads of the thread pool are idle, to remain alive for a time.

Unit : The units of the thread activity hold time , optional units have days, hours, minutes, milliseconds, microseconds, nanoseconds.

workQueue: A task queue that holds a blocking queue for tasks that are waiting to be executed. These tasks are stored before the task is executed, and the work queue stores only the task that executed the Execute method. You can select the following blocking queues: Arrayblockingqueue,linkedblockingqueue,synchronousqueue and Priorityblockingqueue.

threadfactory: Used to set the factory for creating threads , you can set a more meaningful name for each thread created by the thread factory.

handler: Saturation policy , when the queue and thread pool are full, indicating that the thread pools are saturated, a policy must be taken to handle the new tasks submitted. This policy is abortpolicty by default, indicating that an exception is thrown when a new task cannot be processed.

4. Submit a task to the thread pool
You can use two methods to submit tasks to the thread pool, namely execute () and the Submit () method.

The Execute () method is used to commit a task that does not require a return value, so it is not possible to determine whether the task was successfully executed by the thread pool.

The Submit () method is used to submit a task that requires a return value. The thread pool returns an object of the future type, through which the future object can determine whether the task succeeds, and can get the return value through the Get () method of the future, which blocks the current thread from knowing that the task is complete, and using get (long Timeout, the Timeunit unit) method blocks the current thread from returning immediately after a period of time, when the task may not have finished executing.

5. Close the thread pool

You can turn off the thread pool by invoking the shutdown or shutdownnow method of the line pool.

principle : Traversing a worker thread in the thread pool, and then calling the thread's interrupt method One at a time, so that a task that cannot respond to the interrupt may never be terminated .

difference :shutdownnow First sets the status of the thread pool to stop, then attempts to stop all the threads that are executing or pausing the task, and returns a list of pending tasks;

shutdown Just sets the status of the thread pool to shutdown state, and then interrupts all threads that are not performing the task.

You typically call shutdown to close the thread pool, and you can call the Shutdownnow method if the task is not necessarily finished.

We recommend using a bounded queue: it can increase the stability and early warning ability of the system.

Thread pool in Java

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.