Full Java thread pool

Why use the thread pool

The official documents, the thread pool to solve two problems: First, the implementation of a large number of asynchronous task because the thread pool to reduce the preparatory work before the start of the task, such as frequent create a thread, starting the thread, etc., to enhance the performance ; second is to provide a way to bind the resources and the management of resources, can make some basic statistical analysis, such as the number of tasks have been completed and so on.

ExecutorService

Interface, inherited from the Executor, to perform tasks execute Runnable method. ExecutorService provides a management method terminates asynchronous tasks and methods to track the progress of asynchronous tasks by Future object.

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}
复制代码

ExecutorService can be turned off, then no longer accept new tasks, resources can be recycled. Extension method submit execute the method, the object returns a Future for canceling execution or waiting for execution is completed. Can batch tasks.

public interface ExecutorService extends Executor {

    /**
     * 已经提交的任务继续执行,不再接受新的任务
     */
    void shutdown();

    /**
     * 尝试停止正在执行的任务,没有执行的任务不再执行,不再接受新的任务
     * 返回没有执行的任务的列表
     */
    List<Runnable> shutdownNow();

    /**
     * 阻塞直到(所有任务完成(shutdown 后)| 超时 | 当前线程被中断)发生其一
     * 终止时返回 true,反之返回 false
     */
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    /**
     * 提交新任务,并返回一个 Future 对象用于获取执行结果信息
     */
    <T> Future<T> submit(Callable<T> task);
    <T> Future<T> submit(Runnable task, T result);
    Future<?> submit(Runnable task);

    /**
     * 执行给定的任务列表,返回任务结果信息的 Future 列表。可设定超时时间
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                  long timeout, TimeUnit unit)
        throws InterruptedException;

    /**
     * 执行给定的任务列表,返回一个成功完成的任务的结果(如果有)。可设定超时时间
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
复制代码

ThreadPoolExecutor

Inherited from AbstractExecutorService. AbstractExecutorService ExecutorService implements the interface, and add protect method newTaskFor, the method returns to assist in achieving submit Future object. In the process of using the thread pool, use the constructor to the class in most cases, unless it is delayed task or ForkJoin types of tasks.

Construction method

Constructor thread pool has four, will eventually call to the constructor below.

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
复制代码
  • corePoolSize: The number of threads in the thread pool to maintain, even if the thread is free. No idle thread will be destroyed when the task timeout when allowCoreThreadTimeOut = true.

  • maximumPoolSize: task queue after saturation allows you to create a new thread, indicates the number of threads in the thread pool maximum allowed.

  • keepAliveTime: the number of threads in the thread pool is greater than corePoolSize, before terminating the idle thread keepalive time.

  • unit: unit of time.

  • workQueue: task queue. Save only submitted tasks () method of ExecutorService execute. When added to the task queue exceeds the maximum volume, you need to use RejectedExecutionHandler for processing. BlockingQueue some default implementation, more commonly used it is LinkedBlockingQueue, SynchronousQueue, ArrayBlockingQueue; correspond to no limits linked list implementation of queues directly create synchronization queue thread of a particular size array formula queue (intention behind writing a right about this).

  • threadFactory: create a new thread factory. You can customize, such as naming thread and other operations can be implemented. Executors are implemented in a number of plants, such as defaultThreadFactory, it can be modified based on the class, so that they meet custom requirements. The need to achieve newThread method that returns the new thread.

  • handler: When the maximum number of thread pool threads and the queue has been filled, and then came the task can not be dealt with. This is when you need a RejectedExecutionHandler to explain how to deal with the overflow of these tasks. ThreadPoolExecutor the default implementation CallerRunsPolicy, AbortPolicy, DiscardPolicy, DiscardOldestPolicy several types of processors, respectively, as direct execution, interruption, ignoring the task, not to ignore the oldest mission. We can customize the new processor as a new thread processing.

Create rules thread

When a new task is submitted to the thread pool, there are several possible scenarios occur.

  1. There are less than corePoolSize thread pool threads are running, then re-create a new thread, even if some threads in the thread pool idle state, because at this time has not yet reached the core number of threads the thread pool.
  2. The number of thread pool threads is greater than and less than or equal to corePoolSize maximumPoolSize, if the work queue is not saturated, will add a new task to the task queue, not re-created thread; if the work queue is saturated, creating a new thread.
  3. It is equal to the number of threads the thread pool and the task queue maximumPoolSize saturated, thread pooling RejectedExecutionHandler new processing tasks, such as interrupts, ignoring, in this direct execution thread.

ScheduledExecutorService 与 ForkJoinPool

Under normal circumstances the use of ThreadPoolExecutor enough, in addition to manage tasks and delayed periodic task ScheduledExecutorService, based on ForkJoinPool ForkJoinPool ideas implemented here simply mention.

ScheduledExecutorService

Inherited from ExecutorService, it can be executed or executed after a certain time period. Several delays or extended cycle method to perform the task. When tasks submitted by the execute method and submit a new method and ScheduledExecutorService several delays and extensions of the cycle time setting method is non-positive, that this task should be executed immediately.

public interface ScheduledExecutorService extends ExecutorService {

    /**
     * 创建延迟任务,在 delay 延迟之后执行,返回一个 ScheduledFuture 表示执行的状态。
     */
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);

    /**
     * 创建周期执行的任务,初始延迟之后第一次进行执行,周期时间后重复执行。如果执行的时间超过周期时间也不会同时执行,会有一定的延迟再。返回一个 ScheduledFuture 表示执行的状态。
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

    /**
     * 创建周期执行的任务,在初始延迟之后第一次执行,在完成之后的 delay 时间后再次执行。返回一个 ScheduledFuture 表示执行的状态。
     */
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);

}

复制代码

ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor inherited from ThreadPoolExecutor and achieve a delay and cycle approach ScheduledExecutorService newly added. Inherit the parent class constructor, but the task list into a DelayedWorkQueue objects used to implement the delay task.

    public ScheduledThreadPoolExecutor(int corePoolSize,
                                       ThreadFactory threadFactory,
                                       RejectedExecutionHandler handler) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue(), threadFactory, handler);
    }
复制代码

The method can be seen from the configuration called a parent class constructor ThreadPoolExecutor, but maximumPoolSize set Integer.MAX_VALUE, keepAliveTime set to zero. corePoolSize such cases should not be set to 0 and allowCoreThreadTimeOut should not be set to true, or when a new tasking may not be available thread can use thread pool, thread pool meaning there will be no use of.

Delayed tasks execute no sooner than they are enabled, but without any real-time guarantees about when, after they are enabled, they will commence.

Delay task will not be executed before available, but there is no real-time monitoring, it had only performed when it is available (there will be some error). Scheduled at the same time to perform the task order will be submitted in accordance with the mandate, FIFO principle. If the task is not executed before it was revoked, and if you do not set setRemoveOnCancelPolicy is true, then only removed after an initial delay until the end of the queue, it will remove it if canceled after setting.

Tasks performed continuously scheduleAtFixedRate and scheduleAtFixedRate programs do not overlap in time, even running in different threads, the next state obtained before the work began as a result of certain previous execution, thread-safe.

ScheduledThreadPoolExecutor ThreadPoolExecutor rewrite some of the ways to adapt to achieve delayed tasks, this is not too much describes.

ForkJoinPool

Inherited from AbstractExecutorService, for thread pool to run ForkJoinTask task, providing submit, manage and monitor the operation of the method. The difference with the general ExecutorService mainly in the "work-stealing (work-stealing)" idea: all threads in the thread pool to find and execute thread pool is submitted to the task or tasks performed by a thread generated when the task. Use ForkJoinPool in both cases most of the tasks and subtasks can generate multiple sub-tasks to perform is a very effective alternative. When setting asyncMode in the constructor, the task will not be submitted using the FIFO mode of management, the default is to achieve a heap-based mode. Here, however much introduction, follow-up time will be dedicated to write about this, for ForkJoin task can look at Fang Tengfei Gangster talk concurrent (eight) - Fork / Join framework introduced .

Fast thread pool

Java has encapsulated some of the thread pool for our use, under the form of Executors class as newXxxTreadPool method, can quickly establish some common thread pool, here are three common threads to the pool.

  • newFixedThreadPool: Specifies the number of threads, and create a corePoolSize maximumPoolSize consistent, borderless task thread pool queue.
  • newSingleThreadExecutor: create a single worker thread, the thread pool borderless task queue. corePoolSize = maximumPoolSize = 1.
  • newCachedThreadPool: create a reusable thread before the thread pool. If the thread is idle created before and not been destroyed using their new tasks. Using synchronous queue SynchronousQueue. corePoolSize = 0, maximumPoolSize = Integer.MAX_VALUE, keepAliveTime = 60s. That thread you created earlier if there is a new task in the 60s, it can be multiplexed.
  • newWorkStealingPool: to produce work stolen ForkJoinTask thread pool.
  • newScheduledThreadPool: for processing with a delay, the thread pool task of periodic work.

to sum up

When using the thread pool, generally speaking ThreadPoolExecutor clear enough, for ScheduledThreadPoolExecutor and ForkJoinPool for using relatively small, will be used under certain circumstances, we need to know there is such a thing, when needed think can Dollars At Work can be. Doug Lea Gangster some default implementation of these thread pool are written to the Executors class, when simple use of this class method can be used directly.

Long time no write something, write something rhythms are not, and also control the length of inadequate attention next time.

Guess you like

Origin juejin.im/post/5cf7687de51d4550bf1ae817