Java thread pool

Source: Internet
Author: User

Public threadpoolexecutor (int corepoolsize,
int Maximumpoolsize,
Long KeepAliveTime,
Timeunit Unit,
Blockingqueue<runnable> workQueue) {
This (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,
Executors.defaultthreadfactory (), DefaultHandler);
}

jdk1.5 introduces the executor thread pool framework, which decouples the submission and execution of a task by simply defining the task and then submitting it to the thread pool without worrying about how the task is executed, by which thread, and when it executes.Initialize thread pool (4 types)Introduction:

The Java thread pool factory class: Executors class,

Initialize 4 types of thread pools:

Newfixedthreadpool ()
Description: Initializes a thread pool with a specified number of threads, where corepoolsize = = Maxipoolsize, using Linkedblockingquene as the blocking queue
Feature: The thread is not freed even when the thread pool is not able to perform tasks.
Newcachedthreadpool ()
Description: Initialize a thread pool that can cache threads, default cache 60s, thread pool threads can reach Integer.max_value, that is, 2147483647, internal use of synchronousqueue as a blocking queue;
Features: When there is no task execution, when the thread's idle time exceeds KeepAliveTime, the thread resource is automatically freed, and when a new task is submitted, if there is no idle thread, creating a new thread performs the task, which can result in some overhead.
Therefore, it is important to take care to control the number of concurrent tasks and to prevent performance degradation due to the creation of a large number of threads.
Newsinglethreadexecutor ()
Description: Initializes a thread pool with only one threads, internally using Linkedblockingqueue as the blocking queue.
Feature: If the thread ends abnormally, a new thread is recreated to continue the task, and the only thread can guarantee the order in which the submitted tasks are executed
Newscheduledthreadpool ()
Specific: The initialized thread pool can periodically perform the submitted tasks within a specified time, and in the actual business scenario, the thread pool can be used to synchronize data periodically.

Summary: In addition to the Newscheduledthreadpool internal implementation of the special point, the other thread pool inside is based on the Threadpoolexecutor class (executor subclass) implementation.

Threadpoolexecutor Internal specific implementation:

Threadpoolexecutor class constructor Syntax form:

Threadpoolexecutor (Corepoolsize,maxpoolsize,keepalivetime,timeunit,workqueue,threadfactory,handle);

Method Parameters:
 Corepoolsize: Number of core threads
Maxpoolsize: Maximum number of threads
KeepAliveTime: Thread survival time (useful in corepore<*<maxpoolsize case)
Timeunit: Time unit of survival time
WorkQueue: Blocking queue (used to hold tasks waiting to be executed)

Note: For the value of the Workqueue parameter, the JDK provides 4 types of blocking queues to choose from:
arrayblockingqueue: Bounded blocking queue based on array structure, sorting tasks by FIFO;
Inkedblockingquene: A list-based blocking queue that sorts tasks by FIFO with throughput typically higher than

Synchronousquene: A blocking queue that does not store elements, each insert operation must wait for another thread to invoke the remove operation, otherwise the insert operation is always blocked and throughput is usually higher than arrayblockingquene;

Priorityblockingquene: An unbounded blocking queue with priority ;

threadfactory: Thread factory, mainly used to create threads;

Handler: Represents the following four types of values when a policy is rejected for processing a task

Note: When the thread pool is saturated with policy, when the blocking queue is full and there are no idle worker threads, if you continue to submit the task, you must take a policy to handle the task, and the thread pool provides 4 strategies:

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

It is also possible to implement the Rejectedexecutionhandler interface based on the application scenario, customizing the saturation strategy, such as logging or persisting the task that the storage cannot handle.

 the status of the thread pool (5 types)

The Atomicinteger variable ctl is very powerful: it uses a low 29-bit representation of thread pool threads, and a high 3-bit to represent the running state of the thread pools:
1,RUNNING: -1 << count_bits, that is, the high 3 bit is 111, the thread pool of this state will receive new tasks and handle the tasks in the blocking queue;
2,SHUTDOWN: 0 << Count_bits, that is, the high 3 bit is 000, the thread pool of this state will not receive new tasks, but will handle the tasks in the blocking queue;
3,STOP : 1 << count_bits, that is, the high 3 bit is 001, the thread of this state will not receive new tasks, will not handle the tasks in the blocking queue, and will interrupt the running task;
4,tidying : 2 << count_bits, that is, the high 3 bit is 010, this state indicates that thread pool is optimized for threading;
5,TERMINATED: 3 << count_bits, that is, the high 3 bit is 011, the status indicates that the thread pool stops working;

 submit a task to the thread pool (2 types)

There are two ways of doing this:

executor.execute (Runnable command);

Executorservice.submit (callable<t> Task);

execute () internalImplement

1. For the first time, learn the number of threads in the current thread pool through Workcountof ().

If it is less than corepoolsize, the thread is created through Addworker () and the task is executed;

Otherwise, put the task into a blocking queue;

2. If the task can be successfully placed in the blocking queue,

If the current thread pool is a non-running state, the task is removed from the blocking queue and then executed reject () to handle the task;

If the current thread pool is in the running state, you will need to check the thread pool again (because the thread resource may have been freed after the last check), if there are idle threads, and if there is one, perform the task;

3, if the task cannot be placed in the blocking queue, indicating that the blocking queue is full, then the Addwoker () will attempt to create a new thread to perform this task, if the Addwoker () execution fails, indicating that the thread pool has reached Maxpoolsize, The Reject () is executed. processing tasks;

Sumbit () internal implementation

The callable task that will be submitted is encapsulated as a Futuretask object

The Futuretask class implements the Runnable interface so that it can be executed through the Executor.execute () commit futuretask to the thread pool, and finally executes the futuretask run method;

Comparison:

Two methods can submit a task to the thread pool, the return type of the Execute () method is void, it is defined in the executor interface, and the Submit () method can return a future object holding the result of the calculation, which is defined in the Executorservice interface. It extends the executor interface, and other thread pool classes like Threadpoolexecutor and Scheduledthreadpoolexecutor have these methods.

Thread pool shutdown (2 types)

Threadpoolexecutor provides two methods for closing the thread pool, respectively, shutdown () and Shutdownnow (), Where:

Shutdown (): Does not terminate the thread pool immediately, but waits until all tasks in the task cache queue have been executed before terminating, but will no longer accept new tasks

Shutdownnow (): Terminates the thread pool immediately, attempts to break the task in progress, and empties the task cache queue, returning tasks that have not yet been performed

Dynamic adjustment of thread pool capacity

Threadpoolexecutor provides a way to dynamically adjust the size of the thread pool capacity: Setcorepoolsize () and Setmaximumpoolsize (),

Summary:

The number of core threads in the thread pool, when a task is submitted, the thread pool creates a new thread to perform the task until the current number of threads equals corepoolsize, and if the current number of threads is corepoolsize, the task that continues to commit is saved to the blocking queue, waiting to be executed, or if the blocking queue is full, That creates a new thread to perform the current task, until the number of threads in the thread pool reaches maxpoolsize, and then there is a task that only executes reject () to handle the task;

Note: If you execute the Prestartallcorethreads () method of the thread pool, the thread pool creates and starts all core threads in advance.

Reference && Recommendation: http://www.jianshu.com/p/87bff5cc8d8c

Java thread pool

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.