Summary of the use of the Executor interface in Java

  • 2020-04-01 03:55:29
  • OfStack

This article illustrates the use of the Executor interface in Java. Share with you for your reference. The details are as follows:

1. Definition of the Executor interface in Java


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

2. The Executors under static factory methods to create a thread pool:

A) newFixedThreadPool: create a fixed-length thread pool. After reaching the maximum number of threads, the number of threads does not grow.

If a thread ends with an unexpected Exception, a new thread is added to the thread pool.

B) newCachedThreadPool: create a cacheable thread pool. When the pool length exceeds the processing requirements, idle threads can be reclaimed.

C) newSingleThreadPool: create a single-threaded executor.

D) newScheduledThreadPool: creates a fixed-length thread pool and supports timed and periodic task execution.

Something like a Timer. The Timer is based on the absolute time, however, is sensitive to the change of the system clock, and ScheduledThreadPoolExecutor only support relative time.

3. Compare the application summary of Timer

1) Timer is to create a unique thread to execute all Timer tasks. If one task runs out of time, it can cause problems with the accuracy of other timertasks.

2) if the TimerTask throws an uncheck exception, the Timer will generate unexpected behavior. Therefore, ScheduledThreadPoolExecutor can completely replace the Timer.

3) the ExecutorService interface extends Executor to address the lifecycle problem of executing services. The thread pool will include three status: running, shutting down, terminated.

4. Callable and Future

Because Runnable does not return a value, and checked exceptions cannot be thrown, Callable is a better abstraction. (Callable< Void> Represents a task with no return value.
Future describes the life cycle of a task and provides related methods to obtain the result of the task, cancel the task, and check whether the task is completed or canceled.

5.CompletionService incorporates the capabilities of Executor and BlockingQueue.

Its take and poll can block the completion of the task.

I hope this article has been helpful to your Java programming.


Related articles: