Java : ExecutorService with Examples

ExecutorService (Java SE 19 & JDK 19) API Examples.
You will find code examples on most ExecutorService methods.


Summary

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

Class diagram

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final Callable<String> task = () -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(1);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    };

    final var future = executorService.submit(task);

    final var ret = future.get();
    System.out.println("future get : " + ret);
}

// Result
// ↓
//task start
//task end
//future get : abcd

Methods

boolean awaitTermination (long timeout, TimeUnit unit)

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

final var executorService = Executors.newSingleThreadExecutor();
try {
    executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("Run!");

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        } finally {
            System.out.println("task end");
        }
    });
} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(2, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task start
//Run!
//task end
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("Run!");

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        } finally {
            System.out.println("task end");
        }
    });
} finally {
    executorService.shutdown();
}

// Wait 1 second.
final var ret = executorService.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("term 1 : " + ret);

// Wait another 2 seconds.
final var ret2 = executorService.awaitTermination(2, TimeUnit.SECONDS);
System.out.println("term 2 : " + ret2);

// Result
// ↓
//task start
//term 1 : false
//Run!
//task end
//term 2 : true

default void close ()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

System.out.println("-- start --");

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final Callable<Void> task = () -> {
        try {
            System.out.println("  task start");
            System.out.println("  sleep...");
            TimeUnit.SECONDS.sleep(1);
        } finally {
            System.out.println("  task end");
        }
        return null;
    };

    executorService.submit(task);
    System.out.println("submit end");
}

System.out.println("-- end --");

// Result
// ↓
//-- start --
//submit end
//  task start
//  sleep...
//  task end
//-- end --

An example without try-with-resources.

System.out.println("-- start --");

final var executorService = Executors.newSingleThreadExecutor();
try {
    final Callable<Void> task = () -> {
        try {
            System.out.println("  task start");
            System.out.println("  sleep...");
            TimeUnit.SECONDS.sleep(1);
        } finally {
            System.out.println("  task end");
        }
        return null;
    };

    executorService.submit(task);
    System.out.println("submit end");
} finally {
    executorService.close();
}

System.out.println("-- end --");

// Result
// ↓
//-- start --
//submit end
//  task start
//  sleep...
//  task end
//-- end --

<T> List<Future<T>> invokeAll (Collection<? extends Callable<T>> tasks)

Executes the given tasks, returning a list of Futures holding their status and results when all complete.

final var tasks = List.<Callable<String>>of(
        () -> {
            try {
                System.out.println("task 1 : start");
                TimeUnit.SECONDS.sleep(1);
                return "aaa";
            } finally {
                System.out.println("task 1 : end");
            }
        },
        () -> {
            try {
                System.out.println("task 2 : start");
                TimeUnit.SECONDS.sleep(1);
                return "bbb";
            } finally {
                System.out.println("task 2 : end");
            }
        },
        () -> {
            try {
                System.out.println("task 3 : start");
                TimeUnit.SECONDS.sleep(1);
                return "ccc";
            } finally {
                System.out.println("task 3 : end");
            }
        }
);

try (final var executorService = Executors.newFixedThreadPool(3)) {
    System.out.println("-- invoke start --");

    final var futures = executorService.invokeAll(tasks);

    System.out.println("-- invoke end --");

    for (final var future : futures) {
        System.out.println("get : " + future.get());
    }
}

// Result
// ↓
//-- invoke start --
//task 1 : start
//task 2 : start
//task 3 : start
//task 1 : end
//task 2 : end
//task 3 : end
//-- invoke end --
//get : aaa
//get : bbb
//get : ccc

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

Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.

final var tasks = List.<Callable<String>>of(
        () -> {
            try {
                System.out.println("task 1 : start");
                TimeUnit.SECONDS.sleep(1);
                return "aaa";
            } catch (InterruptedException e) {
                System.out.println("task 1 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 1 : end");
            }
        }, () -> {
            try {
                System.out.println("task 2 : start");
                TimeUnit.SECONDS.sleep(3);
                return "bbb";
            } catch (InterruptedException e) {
                System.out.println("task 2 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 2 : end");
            }
        }, () -> {
            try {
                System.out.println("task 3 : start");
                TimeUnit.SECONDS.sleep(5);
                return "ccc";
            } catch (InterruptedException e) {
                System.out.println("task 3 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 3 : end");
            }
        });

try (final var executorService = Executors.newFixedThreadPool(3)) {
    System.out.println("-- invoke start --");

    final var futures = executorService.invokeAll(tasks, 4, TimeUnit.SECONDS);

    System.out.println("-- invoke end --");

    System.out.println("futures size : " + futures.size());

    for (final var future : futures) {
        if (future.isCancelled()) {
            System.out.println("Cancelled!");
            continue;
        }

        System.out.println("future get : " + future.get());
    }

}

// Result
// ↓
//-- invoke start --
//task 1 : start
//task 2 : start
//task 3 : start
//task 1 : end
//task 2 : end
//-- invoke end --
//task 3 : Interrupted!
//task 3 : end
//futures size : 3
//future get : aaa
//future get : bbb
//Cancelled!

<T> T invokeAny (Collection<? extends Callable<T>> tasks)

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do.

final var tasks = List.<Callable<String>>of(
        () -> {
            System.out.println("task 1 : start");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("task 1 : throw IllegalStateException!");
            throw new IllegalStateException();
        }, () -> {
            try {
                System.out.println("task 2 : start");
                TimeUnit.SECONDS.sleep(2);
                return "bbb";
            } catch (InterruptedException e) {
                System.out.println("task 2 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 2 : end");
            }
        }, () -> {
            try {
                System.out.println("task 3 : start");
                TimeUnit.SECONDS.sleep(3);
                return "ccc";
            } catch (InterruptedException e) {
                System.out.println("task 3 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 3 : end");
            }
        });

try (final var executorService = Executors.newFixedThreadPool(3)) {
    System.out.println("-- invoke start --");

    final var ret = executorService.invokeAny(tasks);

    System.out.println("-- invoke end --");

    System.out.println("task ret : " + ret);

}

// Result
// ↓
//-- invoke start --
//task 1 : start
//task 2 : start
//task 3 : start
//task 1 : throw IllegalStateException!
//task 2 : end
//-- invoke end --
//task 3 : Interrupted!
//task 3 : end
//task ret : bbb

<T> T invokeAny (Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)

Executes the given tasks, returning the result of one that has completed successfully (i.e., without throwing an exception), if any do before the given timeout elapses.

final var tasks = List.<Callable<String>>of(
        () -> {
            System.out.println("task 1 : start");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("task 1 : throw IllegalStateException!");
            throw new IllegalStateException();
        }, () -> {
            try {
                System.out.println("task 2 : start");
                TimeUnit.SECONDS.sleep(2);
                return "bbb";
            } catch (InterruptedException e) {
                System.out.println("task 2 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 2 : end");
            }
        }, () -> {
            try {
                System.out.println("task 3 : start");
                TimeUnit.SECONDS.sleep(5);
                return "ccc";
            } catch (InterruptedException e) {
                System.out.println("task 3 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 3 : end");
            }
        });

try (final var executorService = Executors.newFixedThreadPool(3)) {
    System.out.println("-- invoke start --");

    final var ret = executorService.invokeAny(tasks, 3, TimeUnit.SECONDS);

    System.out.println("-- invoke end --");

    System.out.println("task ret : " + ret);

} catch (TimeoutException e) {
    System.out.println("Timeout!");
}

// Result
// ↓
//-- invoke start --
//task 1 : start
//task 2 : start
//task 3 : start
//task 1 : throw IllegalStateException!
//task 2 : end
//-- invoke end --
//task 3 : Interrupted!
//task 3 : end
//task ret : bbb
final var tasks = List.<Callable<String>>of(
        () -> {
            try {
                System.out.println("task 1 : start");
                TimeUnit.SECONDS.sleep(2);
                return "aaa";
            } catch (InterruptedException e) {
                System.out.println("task 1 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 1 : end");
            }
        }, () -> {
            try {
                System.out.println("task 2 : start");
                TimeUnit.SECONDS.sleep(3);
                return "bbb";
            } catch (InterruptedException e) {
                System.out.println("task 2 : Interrupted!");
                return null;
            } finally {
                System.out.println("task 2 : end");
            }
        });

try (final var executorService = Executors.newFixedThreadPool(2)) {
    System.out.println("-- invoke start --");

    final var ret = executorService.invokeAny(tasks, 1, TimeUnit.SECONDS);

    System.out.println("-- invoke end --");

    System.out.println("task ret : " + ret);

} catch (TimeoutException e) {
    System.out.println("Timeout!");
}

// Result
// ↓
//-- invoke start --
//task 1 : start
//task 2 : start
//task 1 : Interrupted!
//task 2 : Interrupted!
//task 1 : end
//task 2 : end
//Timeout!

boolean isShutdown ()

Returns true if this executor has been shut down.

try (final var executorService = Executors.newWorkStealingPool()) {
    final var future = executorService.submit(() -> {
        System.out.println("task start");
        return "abcd";
    });

    final var ret = future.get();
    System.out.println("future get : " + ret);

    System.out.println("isShutdown : " + executorService.isShutdown());
    System.out.println("isTerminated : " + executorService.isTerminated());
}

// Result
// ↓
//task start
//future get : abcd
//isShutdown : false
//isTerminated : false
final var executorService = Executors.newSingleThreadExecutor();
try {
    executorService.submit(() -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        } finally {
            System.out.println("task end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

} finally {

    System.out.println("isShutdown : " + executorService.isShutdown());
    System.out.println("isTerminated : " + executorService.isTerminated());

    executorService.shutdown();
    System.out.println("--- shutdown ---");

    System.out.println("isShutdown : " + executorService.isShutdown());
    System.out.println("isTerminated : " + executorService.isTerminated());
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

System.out.println("--- awaitTermination ---");

System.out.println("isTerminated : " + executorService.isTerminated());

// Result
// ↓
//task start
//isShutdown : false
//isTerminated : false
//--- shutdown ---
//isShutdown : true
//isTerminated : false
//task end
//term : true
//--- awaitTermination ---
//isTerminated : true

boolean isTerminated ()

Returns true if all tasks have completed following shut down.

Please see isShutdown().

void shutdown ()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

final var executorService = Executors.newSingleThreadExecutor();
try {
    final Runnable task1 = () -> {
        try {
            System.out.println("task1 start");
            TimeUnit.SECONDS.sleep(2);

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        } finally {
            System.out.println("task1 end");
        }
    };

    executorService.submit(task1);
    TimeUnit.SECONDS.sleep(1);

} finally {
    executorService.shutdown();
    System.out.println("--- shutdown ---");
}

try {
    executorService.submit(() -> System.out.println("task2"));

} catch (RejectedExecutionException e) {
    System.out.println("submit : Reject!");
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task1 start
//--- shutdown ---
//submit : Reject!
//task1 end
//term : true

List<Runnable> shutdownNow ()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

final var executorService = Executors.newSingleThreadExecutor();
try {
    executorService.submit(() -> {
        try {
            System.out.println("task1 : start");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("task1 : run");

        } catch (InterruptedException e) {
            System.out.println("task1 : Interrupted!");
        } finally {
            System.out.println("task1 : end");
        }
    });
    executorService.submit(() -> {
        System.out.println("task2 : run");
    });
    executorService.submit(() -> {
        System.out.println("task3 : run");
    });

    TimeUnit.SECONDS.sleep(1);

} finally {
    System.out.println("--- shutdownNow ---");
    final var notExecutedTasks = executorService.shutdownNow();

    TimeUnit.SECONDS.sleep(1);

    System.out.println("--- not executed tasks ---");
    System.out.println("size : " + notExecutedTasks.size());

    for (final var task : notExecutedTasks) {
        task.run();
    }
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task1 : start
//--- shutdownNow ---
//task1 : Interrupted!
//task1 : end
//--- not executed tasks ---
//size : 2
//task2 : run
//task3 : run
//term : true
final var executorService = Executors.newSingleThreadExecutor();
try {
    executorService.submit(() -> {
        try {
            System.out.println("task1 : start");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("task1 : run");

        } catch (InterruptedException e) {
            System.out.println("task1 : Interrupted!");
        } finally {
            System.out.println("task1 : end");
        }
    });

    TimeUnit.SECONDS.sleep(1);

} finally {
    System.out.println("--- shutdownNow ---");
    executorService.shutdownNow();
}

TimeUnit.SECONDS.sleep(1);

try {
    executorService.submit(() -> {
        System.out.println("task2 : run");
    });

} catch (RejectedExecutionException e) {
    System.out.println("submit : Reject!");
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.println("term : " + ret);

// Result
// ↓
//task1 : start
//--- shutdownNow ---
//task1 : Interrupted!
//task1 : end
//submit : Reject!
//term : true

Future<?> submit (Runnable task)

Submits a Runnable task for execution and returns a Future representing that task.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final Runnable task = () -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("task run");

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        } finally {
            System.out.println("task end");
        }
    };

    final var future = executorService.submit(task);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- future get --");
    future.get();

    System.out.println("future isDone : " + future.isDone());
}

// Result
// ↓
//task start
//-- future get --
//task run
//task end
//future isDone : true

<T> Future<T> submit (Runnable task, T result)

Submits a Runnable task for execution and returns a Future representing that task.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final Runnable task = () -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            System.out.println("task run");

        } catch (InterruptedException e) {
            System.out.println("Interrupted!");
        } finally {
            System.out.println("task end");
        }
    };

    final var future = executorService.submit(task, "abcd");

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- future get --");
    final var ret = future.get();

    System.out.println("future ret : " + ret);
    System.out.println("future isDone : " + future.isDone());
}

// Result
// ↓
//task start
//-- future get --
//task run
//task end
//future ret : abcd
//future isDone : true

<T> Future<T> submit (Callable<T> task)

Submits a value-returning task for execution and returns a Future representing the pending results of the task.

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final Callable<String> task = () -> {
        try {
            System.out.println("task start");
            TimeUnit.SECONDS.sleep(2);
            return "abcd";
        } finally {
            System.out.println("task end");
        }
    };

    final var future = executorService.submit(task);

    TimeUnit.SECONDS.sleep(1);

    System.out.println("-- future get --");
    final var ret = future.get();

    System.out.println("future ret : " + ret);
    System.out.println("future isDone : " + future.isDone());
}

// Result
// ↓
//task start
//-- future get --
//task end
//future ret : abcd
//future isDone : true

Methods declared in Executor

execute

Please see the link below.


Related posts

To top of page