[Java concurrency] The Executor framework and thread pool configuration and usage, javaexecutor

Source: Internet
Author: User

[Java concurrency] The Executor framework and thread pool configuration and usage, javaexecutor
[Java concurrency] Executor Framework mechanism and thread pool Configuration

1. The Executor framework is introduced in Java 5. It uses the thread pool mechanism internally and. util. in the cocurrent package, this framework is used to control the startup, execution, and shutdown of threads, which can simplify concurrent programming operations. Therefore, after Java 5, it is better to use Executor to start a Thread than to use the Thread start method, which is easier to manage and more efficient (implemented using the Thread pool to save overhead ).

Executor frameworks include Executor, Executors, ExecutorService, AbstractExecutorService, ThreadPoolExecutor, CompletionService, Future, and Callable.

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

Executor is a simple interface, but it is the basis of the entire execution framework. It splits the submission and execution of tasks and uses Runnable to represent tasks, therefore, Executor can also be viewed as a producer-consumer mode. The operations for submitting a task are equivalent to those for the producer, and the threads for executing the task are equivalent to the consumers. Executor also supports the lifecycle, statistical information collection, application management, 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

ExecutorService extends Executor, which is a more widely used sub-class interface than Executor. It provides lifecycle management methods and can trace the execution status of one or more asynchronous tasks and return the Future method. It mainly includes three states: running, shutting down, and terminating. After the job is created, it enters the running status. When the shutdown () method is called, the job is closed smoothly. ExecutorService no longer accepts new jobs, but it is still waiting for the submitted jobs to complete, shutdownNow () is simple and crude. It directly tries to close all tasks and does not receive them.

AbstractExecutorServiceExecutorService implementation by default

ThreadPoolExecutor thread pool. You can call the static factory method below Executors to create a thread pool and return an ExecutorService object.

Executors

A series of static factory methods are provided to create various thread pools:

1. newFixedThreadPool (int nThreads): Creates a thread pool, which re-uses a fixed number of threads and runs the thread in the shared unbounded queue. At any time, most threads will be active processing tasks. If you submit additional tasks when all threads are active, they will wait in the queue until one thread is available. If any thread is terminated due to a fault in the execution process before it is closed, a new thread will be executed when subsequent tasks need to be executed. The thread in the pool will exist until ExecutorService explicitly closes the service.

2. newCachedThreadPool (): Creates a thread pool and a new thread as needed. However, when available, the previously constructed thread is reused. These pools generally improve the performance of programs that execute many short-term asynchronous tasks. If available, execute calls will reuse previously constructed threads. If no existing thread is available, a new thread is created and added to the pool. Threads that are not used within 60 seconds are terminated and deleted from the cache. Therefore, a pool with enough idle time will not consume any resources. The specific timeout value can be set.

3. newSingleThreadExecutor (): creates an executor that uses a single worker thread to operate an unbounded queue. (Note: If this single thread is terminated due to execution failure before it is closed, a new thread will appear when a subsequent task needs to be executed .) Tasks are executed in sequence, and no task is active at any given time. Unlike other equivalent newFixedThreadPool (1), the returned execution program is not reconfigured to use other threads.

4. newScheduledThreadPool (int corePoolSize): Creates a thread pool that can run scheduled commands after a given delay or regularly. Similar to Timer.

In general, CachedTheadPool usually creates the same number of threads as required during program execution and stops creating new threads when it recycles old threads. Therefore, CachedTheadPool is the preferred choice for reasonable Executor, fixedThreadPool is required only when this method causes problems (for example, when a large number of connection-oriented threads are required. -- Thinking in Java version 4

Ii. Use thread pool Configuration

Although the Executor framework can efficiently manage threads, not all tasks are suitable for all Executor execution policies, which also reduces performance and efficiency.

1. Thread hunger deadlock

As long as the tasks in the thread pool need to wait for resources or conditions that must be provided by other tasks in the pool for an indefinite period, but the tasks have not been executed by threads in the work queue, this will cause thread hunger and deadlock. For example, assume that only single-thread Executor is running, and task A can continue to wait until the result of Task B is finished. Therefore, task A is A single-thread, task B has been unable to run and is waiting for task A to complete. So the two tasks waited for each other, causing a deadlock. It can also appear in a larger thread pool, unless the thread pool is large enough.

To submit this dependent Executor, you need to avoid hunger deadlock. Therefore, you need to consider the thread pool size limit or configuration limit.

2. Run a long task

Long-running tasks not only cause thread pool blocking, but also increase the service time of Short-running tasks, reducing the responsiveness of the services managed by Executor.

To reduce the impact of a long task, you can set the time for the task to wait for resources. If the wait times out, mark the task failure, stop the task, or execute the task later. This method ensures that the task can always be executed. If the thread pool is always congested, consider whether the thread pool is too small.

ThreadPoolExecutor provides a constructor that can be customized by configuring the thread pool as needed.

Public ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue <Runnable> workQueue, ThreadFactory threadFactory, Volume handler) // The last two parameters are optional.

Specific ThreadPoolExecutor parameter configuration

CorePoolSize

The number of core threads, the core thread will remain alive, even if no task needs to be processed. When the number of threads is smaller than the number of core threads, even if the existing threads are idle, the thread pool will first create a new thread to process the task, rather than directly handing it over to the existing thread for processing. The Core Thread times out and exits when allowCoreThreadTimeout is set to true. By default, it does not exit.

MaximumPoolSize

When the number of threads is greater than or equal to the core thread and the task queue is full, a new thread is created in the thread pool until the number of threads reaches maxPoolSize. If the number of threads is equal to maxPoolSize and the task queue is full, the processing capacity of the thread pool is exceeded. The thread pool rejects the processing of the task and throws an exception.

KeepAliveTime: the idle time allowed by the thread pool to maintain the thread

Unit: the unit of idle time allowed by the thread pool maintenance thread.

WorkQueue: The Buffer Queue used by the thread pool.

Handler: processing policy of the thread pool to reject tasks

When a task is added to the thread pool through the execute (Runnable) method:

1. When the thread pool is smaller than corePoolSize, a new thread will be created for the newly submitted task, even if there are Idle threads in the thread pool.

2. When the thread pool reaches corePoolSize, the newly submitted task will be placed in workQueue, waiting for scheduling and execution of the task in the thread pool.

3. When workQueue is full and maximumPoolSize> corePoolSize is reached, a new thread is created to execute the task.

4. When the number of submitted tasks exceeds maximumPoolSize, the newly submitted tasks are processed by RejectedExecutionHandler.

5. When the thread pool exceeds the corePoolSize thread and the idle time reaches keepAliveTime, close the idle thread.

6. When allowCoreThreadTimeOut (true) is set, when the idle time of the corePoolSize thread in the thread pool reaches keepAliveTime, it is also disabled.

Java Learning Group 669823128

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.