"Java concurrency" executor framework mechanism and thread pool configuration using __ thread pool

Source: Internet
Author: User
Tags terminates
"Java concurrency" executor framework mechanism and thread pool configuration usage

One, executor framework
The executor framework, introduced in Java 5, uses a thread pool mechanism that simplifies concurrent programming operations by controlling the start, execution, and shutdown of threads under the Java.util.cocurrent package. Therefore, after Java 5, booting a thread through executor is better, more manageable, more efficient (with thread pooling, and cost savings) than using thread's Start method.

Executor Framework mainly includes: Executor,executors,executorservice,abstractexecutorservice,threadpoolexecutor,completionservice , future,callable and so on.

Executor

Public interface Executor {
    void execute (Runnable command);
}

Executor is a simple interface, but it is the basis of the entire implementation framework, the task of the submission and execution of the decomposition, and runnable to represent the task, so executor can also be seen as a producer-consumer model, the operation of submitting tasks equivalent to the producer, Threads that perform tasks are equivalent to consumers. The executor implementation also provides support for the lifecycle, as well as mechanisms for statistical information collection, application management mechanisms, and performance monitoring.

Executorservice

Public interface Executorservice extends Executor {
void shutdown ();
List<runnable> Shutdownnow ();
Boolean IsShutDown ();
Boolean isterminated ();
Boolean awaittermination (long timeout, timeunit unit) throws interruptedexception;
//........ Other methods

The Executorservice extension Executor is a more extensive subclass interface than executor, which provides a way to lifecycle management and a way to track the execution status of one or more asynchronous tasks back to future. It mainly consists of three states: Run, close, terminate. When the shutdown () method is invoked, it goes into a flat shutdown state, Executorservice no longer accepts the new task, but waits for the completed task to complete, shutdownnow () is simply rude and tries to close all tasks directly. is not receiving a task.

Abstractexecutorservice
Default implementation of Executorservice execution method

Threadpoolexecutor
Thread pool, you can create a thread pool and return a Executorservice object by calling executors the following static factory method.

Executors
provides a series of static factory methods for creating various thread pools:
1,newfixedthreadpool (int nthreads): Creates a thread pool that uses a fixed number of threads that run in a shared, unbounded queue. At any time, most threads will be active processing tasks. If additional tasks are committed when all threads are active, they wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new thread is executed when a successor task is required. The threads in the pool will exist until Executorservice explicitly performs the service shutdown.
2,newcachedthreadpool (): Create a thread pool, create new threads as needed, but reuse previously constructed threads when available. These pools typically improve the performance of programs that perform many short asynchronous tasks. If available, calls to execute reuse the previously constructed thread. If no existing threads are available, a new thread is created and added to the pool. Threads that are not used within 60 seconds are terminated and removed from the cache. As a result, a pool that is idle enough for a long time will not consume any resources. The specific time-out period can be set.
3,newsinglethreadexecutor (): creates an executor that uses a single worker thread to manipulate an unbounded queue. (Note that if this single thread terminates because of a failure to perform before shutdown, a new thread will appear when a successor task is required.) Tasks are guaranteed to execute sequentially, and no task is active at any given time. Unlike other equivalent Newfixedthreadpool (1), the returned executor guarantees that it will not be reconfigured to use another thread.
4, newscheduledthreadpool (int corepoolsize): creates a thread pool that can schedule commands to run after a given delay, or to execute on a regular basis. Similar to a timer.

In general, Cachedtheadpool typically creates the same thread as the desired number of threads during program execution, and then stops creating new threads when it reclaims old threads, so it is a reasonable executor choice. You need to consider using Fixedthreadpool only if this method raises a problem, such as when you need a large number of threads that are connected for a long time. --"Thinking in Java" fourth edition

two, thread pool configuration usage
Although the executor framework can manage threads efficiently, not all tasks are suitable for executor all execution policies, which can also degrade performance and efficiency.
1, Thread starvation deadlock
As long as the tasks in the thread pool need to wait indefinitely for resources or conditions that must be provided by other tasks in the pool, the task is still not wired to execute in the work queue, which can cause thread starvation deadlock. Take a chestnut, suppose only single-threaded executor, at this time a task is running, the a task waits for the result of the B task to be able to continue, then waits, but at this time is single-threaded, the B task has not been able to run, it waits for a task to end. So the two tasks wait for each other, causing deadlock. can also occur in larger thread pools unless the thread pool is large enough.
To commit this dependent executor, you need to avoid starvation deadlocks, so you need to consider thread pool size limits or configuration restrictions.

2, run a long time task
Performing long tasks not only causes thread pools to block, but even increases service time for short tasks, reducing the responsiveness of executor-managed services.
mitigating the impact of long tasks, you can limit the time that a task waits for a resource. If you wait for a timeout, the tag task fails, and then the task is aborted or the task is later executed. This approach guarantees that the task will always continue. If the thread pool is always blocked, consider whether the thread pool is set too small.

About setting the size estimate for the thread pool you can read this blog post.
http://ifeve.com/how-to-calculate-threadpool-size/

Threadpoolexecutor provides a construction method that configures the thread pool to be customized according to requirements

Public threadpoolexecutor (int corepoolsize,
                          int maximumpoolsize,
                          long KeepAliveTime,
                          timeunit Unit,
                          blockingqueue<runnable> Workqueue,
                          Threadfactory threadfactory,
                          Rejectedexecutionhandler handler)//The latter two parameters are optional parameters

Specific Threadpoolexecutor parameter configuration
corepoolsize
Core threads, the core threads will remain alive, even if there is no task to process. When the number of threads is less than the number of core threads, even if an existing thread is idle, the thread pool takes precedence over the creation of a new thread to handle the task rather than directly to the existing thread. The core thread will time out when the Allowcorethreadtimeout is set to true and will not exit by default.
maximumpoolsize
When the number of threads is greater than or equal to the core thread, and the task queue is full, the line Cheng creates a new thread until the number of threads reaches Maxpoolsize. If the number of threads is equal to maxpoolsize and the task queue is full, the thread pool is out of processing capacity, and the thread pool rejects the task and throws an exception.
KeepAliveTime: thread pool maintains idle time allowed by threads
Unit : the units in which the thread pool maintains the idle time allowed by threads
workqueue: buffer queues used by the thread pool
handler: thread pool processing policy for reject tasks

When a task is added to the thread pool through the Execute (Runnable) method:
1. When the thread pool is less than corepoolsize, the new submit task creates a new thread to perform the task, even if there are idle threads in the thread pool.
2. When the thread pool reaches corepoolsize, the new commit task is placed in the Workqueue, waiting for the task to be scheduled to execute in the thread pool.
3. When the Workqueue is full and maximumpoolsize>corepoolsize, the new submit task creates a new thread to perform the task.
4. When the number of submitted tasks exceeds maximumpoolsize, the new submit task is handled by Rejectedexecutionhandler.
5. When the thread pool exceeds the corepoolsize thread, when the idle time reaches KeepAliveTime, the idle thread is closed
6. When the Allowcorethreadtimeout (true) is set, the corepoolsize thread idle time in the thread pool reaches KeepAliveTime and closes.

All of the above are reading "Java Programming ideas"-Concurrent and "Java Concurrent programming practice" notes, do not like to spray.

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.