Java : Executor with Examples

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


Summary

An object that executes submitted Runnable tasks. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.

Class diagram

try (final var executorService = Executors.newSingleThreadExecutor()) {
    final Runnable command = () -> {
        System.out.println("  command start");
        System.out.println("  thread id = " + Thread.currentThread().threadId());
    };

    System.out.println("-- execute start --");
    System.out.println("thread id = " + Thread.currentThread().threadId());
    executorService.execute(command);
    System.out.println("-- execute end --");
}

System.out.println("-- executor terminated --");

// Result
// ↓
//-- execute start --
//thread id = 1
//-- execute end --
//  command start
//  thread id = 33
//-- executor terminated --

Methods

void execute (Runnable command)

Executes the given command at some time in the future.

Please see also the code example in the summary.

class DirectExecutor implements Executor {
    public void execute(Runnable command) {
        command.run();
    }
}

final var executor = new DirectExecutor();
executor.execute(() -> System.out.println("Run!"));

// Result
// ↓
//Run!

Related posts

To top of page