Java.util.concurrent.ExecutorService interface with Examples

The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads and that determine the shutdown status.

The ExecutorService interface is implemented in a utility class called Executors. It defines methods that provide an implementation of the ExecutorService interface and many other interfaces, with some default settings.

Class heirarchy:

java.util.concurrent
  ↳ Interface ExecutorService

Implementing Sub-Interfaces:

ScheduledExecutorService

Implementing Classes:

AbstractExecutorService
ForkJoinPool
ScheduledThreadPoolExecutor
ThreadPoolExecutor

Methods in Executor interface:

  1. shutdown()– When invoked the function causes all the currently executing tasks to terminate after completion in the order in which they were started and rejects any new incoming tasks.

    Syntax:

    void shutdown()

  2. shutdownNow()– On invocation the function forcefully terminates all the tasks, regardless of their current state i.e running, waiting or ready. The lists of tasks that were in ready state in returned.

    Syntax:

    List<Runnable> shutdownNow()

  3. isShutdown()– The function tells whether the invoking executor is shutdown or not. Returns true if shutdown, otherwise returns false.

    Syntax:

    boolean isShutdown()

  4. isTerminated()– The function checks if all the tasks have been completed post shutdown. Return true if completed, otherwise returns false.

    Syntax:

    boolean isTerminated()

  5. awaitTermination()– The function waits for all the tasks to complete their execution after a shutdown request is found. It waits for the time specified by the timelimit argument.

    Syntax:

    boolean awaitTermination(long timelimit, TimeUnit unit) throws InterruptedException

  6. submit()– The function adds a task that returns a result to the list of executing tasks for execution. It returns a Future object which returns the result of the task after completion.

    Syntax:

    1. <T> Future<T> submit(Callable<T> task)
    2. <T> Future<T> submit(Runnable task, T result)
    3. Future submit?(Runnable task)

  7. invokeAll()– The function executes all the tasks contained in the collection. The list of Future objects is returned which contains the status and return values of the various tasks.

    Syntax:

    1. <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException

    2. <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException

  8. invokeAny()– The function executes all the tasks contained in the collection. On completion of any single task it returns its result and all the other tasks are cancelled.

    Syntax:

    1. <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

    2. <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException

Example demonstrating an Executors

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate ExecutorService interface
  
import java.util.concurrent.*;
  
public class SimpleExecutor {
  
    public static void main(String[] args)
    {
        CountDownLatch cd1 = new CountDownLatch(5);
        CountDownLatch cd2 = new CountDownLatch(5);
        CountDownLatch cd3 = new CountDownLatch(5);
        CountDownLatch cd4 = new CountDownLatch(5);
  
        ExecutorService es = Executors.newFixedThreadPool(2);
  
        System.out.println("Starting");
  
        es.execute(new MyThread(cd1, "A"));
        es.execute(new MyThread(cd2, "B"));
        es.execute(new MyThread(cd3, "C"));
        es.execute(new MyThread(cd4, "D"));
  
        try {
            cd1.await();
            cd2.await();
            cd3.await();
            cd4.await();
        }
        catch (InterruptedException e) {
            System.out.println(e);
        }
  
        es.shutdown();
        System.out.println("Done");
    }
}
  
class MyThread implements Runnable {
    String name;
    CountDownLatch latch;
  
    MyThread(CountDownLatch latch, String name)
    {
        this.name = name;
        this.latch = latch;
  
        new Thread(this);
    }
  
    public void run()
    {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + ":  " + i);
            latch.countDown();
        }
    }
}

chevron_right


Output:

Starting
A:  0
A:  1
A:  2
A:  3
A:  4
C:  0
C:  1
C:  2
C:  3
C:  4
D:  0
D:  1
D:  2
D:  3
D:  4
B:  0
B:  1
B:  2
B:  3
B:  4
Done

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.