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

Source: Internet
Author: User
Tags terminates

Tag: Wait resource static Factory method throws exception response ISS Boolean row ice

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

One, the Executor Framework executor framework is introduced in Java 5, the internal use of the thread pool mechanism, under the Java.util.cocurrent package, through the framework to control the start, execution and shutdown of threads, can simplify the operation of concurrent programming. Therefore, after Java 5, starting a thread through executor is better, easier to manage, and more efficient than using thread's Start method (implemented with thread pooling, saving overhead).

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

Executor
Executor {    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 decomposition, and runnable to represent the task, so executor can also be seen based on the producer-consumer model, the operation of the submission of the task equivalent to the producer, The thread that performs the task corresponds to the consumer. The implementation of executor also provides support for the lifecycle, as well as mechanisms such as statistical information collection, application management mechanisms, and performance monitoring.

Executorservice
PublicInterfaceExecutorserviceExtendsexecutor {void shutdown ();  list<runnable> shutdownnow ()  boolean isshutdown (); boolean isterminated  (); boolean awaitTermination (long timeout, timeunit unit) throws Interruptedexception; //... Other methods                 

Executorservice extension Executor is a more extensive subclass interface than executor, which provides a method for lifecycle management and a way to track the performance of one or more asynchronous tasks back to the future. It mainly consists of three states: Run, close, terminate. Once created, it goes into a running state, and when the shutdown () method is called, it goes into a flat shutdown state, Executorservice no longer accepts new tasks, but it waits for the completed task to be submitted, Shutdownnow () is simply rude and tries to close all tasks directly, The task is not being received.

Default implementation of the Abstractexecutorserviceexecutorservice 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 re-uses a fixed number of threads that run in the shared unbounded queue. At any time, most threads will be the active processing task. If additional tasks are committed while all threads are active, they will wait in the queue until one thread is available. If any thread terminates due to a failure during the execution of the shutdown, a new thread will be executed when a successor task is required. The threads in the pool will exist until Executorservice explicitly executes the service shutdown.

2,newcachedthreadpool (): Creates a thread pool, creates a new thread as needed, but reuses the previously constructed thread when it is available. These pools typically improve the performance of programs that perform many short-term asynchronous tasks. If available, the call to execute reuses the previously constructed thread. If there are no existing threads available, a new thread is created and added to the pool. Threads that were not used within 60 seconds are terminated and removed from the cache. Therefore, a pool that is idle long enough will not consume any resources. The specific timeout period can be set.

3,newsinglethreadexecutor (): Creates an executor that uses a single worker thread to operate an unbounded queue. (Note that if this single thread terminates due to execution failure 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 is guaranteed not to 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 periodically. Similar to a timer.

In general, Cachedtheadpool usually creates the same number of threads as required during program execution and then stops creating a new thread when it recycles the old thread, so it is the preferred choice for a reasonable executor, You only need to consider using fixedthreadpool when this approach can cause problems, such as when you need a large number of long-face connection threads. --"Thinking in Java" version fourth

two, thread pool configuration uses

While the executor framework manages threads efficiently, not all tasks are appropriate 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 some 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 causes a thread starvation deadlock. For a chestnut, assuming only single-threaded executor, at this time a task is running, a task waiting for the results of the B task can continue, and then wait, but at this time is single-threaded, b task has been unable to run, it at the end of a task. So the two tasks wait for each other, causing a deadlock. It can also occur in a larger pool of threads, unless the thread pool is large enough.

Submitting this dependent executor requires avoiding starvation deadlocks, so you need to consider thread pool size limits or configuration restrictions.

2, run a long time task

Executing a long task not only causes the thread pool to block, but it also increases the service time of short-running tasks and reduces the responsiveness of executor-managed services.

Mitigate the impact of long-time tasks, and you can limit the time that a task waits for resources. If you wait for a timeout, the flagged task fails, then aborts the task or executes the task at a later time. This approach guarantees that the task will always continue to be carried out. If the thread pool is always blocked, consider whether the thread pool is set too small.

Threadpoolexecutor provides a construction method that allows you to configure the thread pool as needed to customize

Threadpoolexecutor(int corepoolsize,                          //After two arguments are optional parameters  

Specific configuration of threadpoolexecutor parameters

corepoolsize

Core threads, the core thread will remain alive even if no tasks are required to be processed. When the number of threads is less than the number of core threads, even if an existing thread is idle, the thread pool prioritizes the creation of new threads to handle tasks rather than handing them over to existing threads. The core thread exits when Allowcorethreadtimeout is set to true, and does 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 pool 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 processing power of the thread pool is exceeded, and the thread pool rejects processing the task and throws an exception.

KeepAliveTime: The thread pool maintains the idle time allowed by threads

Unit: The thread pool maintains the units of idle time allowed by threads

WorkQueue: Buffer queue used by the thread pool

Handler: thread pool processing policy for rejected tasks

When a task is added to the thread pool by the Execute (Runnable) method:

1. When the thread pool is less than corepoolsize, the new commit task creates a new thread to perform the task, even if there are idle threads in the thread pools.

2. When the thread pool reaches corepoolsize, the new commit task is put into Workqueue, waiting for the task to be scheduled to execute in the thread pool.

3. When Workqueue is full and maximumpoolsize>corepoolsize, the new commit task creates a new thread to perform the task.

4. When the number of submitted tasks exceeds maximumpoolsize, the new submission task is handled by Rejectedexecutionhandler.

5. When the thread pool exceeds the corepoolsize thread and the idle time reaches KeepAliveTime, the idle thread is closed

6. When Allowcorethreadtimeout (true) is set, the corepoolsize thread idle time in the thread pool reaches KeepAliveTime will also close.

Java Learning Group 669823128

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

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.