cs notebook1
  • Introduction
  • sort algorithm
  • Overloading VS Overriding
  • multithreading
  • Concurrency0
  • Concurrency1
  • ExecutorService
  • iteration & recursion
  • IO
  • Marker interface(Serializable, Clonnable&Remote)
  • Jackson Library
  • java.lang.System.*
  • Virtual Memory
  • Java ClassLoader
  • interfaceVSabstractClass
  • ENUM
Powered by GitBook
On this page
  • http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/
  • 1. the usage of executor
  • 2.Instantiating ExecutorService
  • 3. Assigning Tasks to the ExecutorService
  • 4. Shutting Down an ExecutorService

Was this helpful?

ExecutorService

PreviousConcurrency1Nextiteration & recursion

Last updated 6 years ago

Was this helpful?

Executorservice is a framework provided by the JDK which simplifies the execution of tasks in asynchronous mode. ExecutorService automatically provides a pool of threads and API for assigning tasks to it.

1. the usage of executor

The Concurrency API introduces the concept of an ExecutorServiceas a higher level replacement for working with threads directly. Executors are capable of running asynchronous tasks and typically manage a pool of threads, so we don't have to create new threads manually. All threads of the internal pool will be reused under the hood for revenant tasks, so we can run as many concurrent tasks as we want throughout the life-cycle of our application with a single executor service.

The classExecutorsprovides convenient factory methods for creating different kinds of executor services.

ExecutorService

2.Instantiating ExecutorService

2.1 Factory Methods of the Executors Class

eg:

ExecutorService executor = Executors.newFixedThreadPool(10);

2.2 Directly create an ExecutorService

For example, the _ThreadPoolExecutor _class has a few constructors which can be used to configure an executor service and its internal pool.

eg:

ExecutorService executorService = new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

eg:

ExecutorService executor = Executors.newCachedThreadPool();

3. Assigning Tasks to the ExecutorService

Runnable runnableTask = () -> {
    try {
        TimeUnit.MILLISECONDS.sleep(300);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
};

Callable<String> callableTask = () -> {
    TimeUnit.MILLISECONDS.sleep(300);
    return "Task's execution";
};

List<Callable<String>> callableTasks = new ArrayList<>();
callableTasks.add(callableTask);
callableTasks.add(callableTask);
callableTasks.add(callableTask);

Tasks can be assigned to the ExecutorService _using several methods, including _execute(), which is inherited from the Executor _interface, and also _submit(), invokeAny(), invokeAll().

execute() method is void, and it doesn't give any possibility to get the result of task's execution or to check the task's status(is it running or executed?)

executorService.execute(runnableTask);

submit() submits a Callable or a Runnable task to an ExecutorService and returns a result of type Future.

Future interface has methods to obtain the result generated by a Callable object and to manage its state.

Future<String> future = executorService.submit(callableTask);

invokeAny() _assigns a collection of tasks to an _ExecutorService, _causing each to be executed, and returns the result of a successful execution of one task (if there was a successful execution)._

String result = executorService.invokeAny(callableTasks);

invokeAll() assigns a collection of tasks to an ExecutorService, causing each to be executed, and returns the result of all task executions in the form of a list of objects of type Future.

List<Future<String>> futures = executorService.invokeAll(callableTasks);

4. Shutting Down an ExecutorService

shutdown() method doesn’t cause an immediate destruction of the _ExecutorService. _It will make the _ExecutorService _stop accepting new tasks and shut down after all running threads finish their current work.

executorService.shutdown();

shutdownNow() method tries to destroy the ExecutorService immediately, but it doesn’t guarantee that all the running threads will be stopped at the same time. This method returns a list of tasks which are waiting to be processed. It is up to the developer to decide what to do with these tasks.

List<Runnable> notExecutedTasks = executorService.shutDownNow();
executorService.shutdown();
try{
    if(!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)){
        executorService.shutdownNow();
    }
}catch(InterruptedException e){
    executorService.shutdownNow();
}

Because ExecutorService _is an interface, an instance of any its implementations can be used. There are several implementations to choose from in the [_java.util.concurrent]() package or you can create your own.

One good way to shut down the ExecutorService (which is also ) is to use both of these methods combined with the _awaitTermination() _method. With this approach, the _ExecutorService _will first stop taking new tasks, the wait up to a specified period of time for all tasks to be completed. If that time expires, the execution is stopped immediately:

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html
newFixedThreadPool
newCachedThreadPool
recommended by Oracle
http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/
https://www.baeldung.com/java-executor-service-tutorial