00:00

Executor Interface in Java: The Root of the Executor Framework

Last updated:

The Executor interface in Java is the smallest building block of the Executor Framework. It has one method, execute(Runnable), and it hides how a task is run: on a new thread, on a pooled thread, or even on the calling thread.

This tutorial explains what that single method promises, where Executor sits in the hierarchy, and how to write your own executors.

1. What Is the Executor Interface?

Executor is an interface in java.util.concurrent, added in Java 5. Code that has work to do calls execute(task); the Executor implementation decides which thread runs it and when.

This separates two concerns. The submitting code describes what to run. The executor decides how to run it: the threading policy, queuing and limits. You can change that policy without touching the code that creates tasks.

2. Syntax

Executor.java (JDK declaration)
public interface Executor {
    void execute(Runnable command);
}

The documented contract is short. The task runs at some time in the future, possibly in a new thread, a pooled thread or the calling thread. execute() throws RejectedExecutionException if the task cannot be accepted, and NullPointerException if it is null.

3. Executor Interface Hierarchy

Executor interface hierarchyExecutor is the root interface. ExecutorService extends Executor. ScheduledExecutorService extends ExecutorService. AbstractExecutorService implements ExecutorService, and ThreadPoolExecutor and ForkJoinPool extend AbstractExecutorService.«interface»Executorthis pageexecute(Runnable)«interface»ExecutorServicesubmit(…), invokeAll(…)shutdown(), close()«interface»ScheduledExecutorServiceschedule(…)«abstract class»AbstractExecutorServicesubmit(), invokeAll(), invokeAny()«class»ThreadPoolExecutor«class»ForkJoinPoolextendsimplementsinterfaceabstract classclass

Swipe sideways to see the whole diagram.

  • Executor (interface): The root: one method, execute(Runnable), with no lifecycle and no results.
  • ExecutorService (interface): Extends Executor with submit(), bulk execution and lifecycle methods such as shutdown() and close().
  • ScheduledExecutorService (interface): Extends ExecutorService with delayed and periodic execution.
  • AbstractExecutorService (abstract class): Implements submit(), invokeAll() and invokeAny() on top of execute().
  • ThreadPoolExecutor and ForkJoinPool (classes): The JDK's main concrete executors; both ultimately implement Executor.execute().

4. Example: An Executor That Runs Tasks on the Caller's Thread

Nothing in the contract requires a new thread. This executor runs each task immediately, which is useful in unit tests where you want asynchronous code to behave synchronously.

CallerThreadExecutor.java
import java.util.concurrent.Executor;

public class CallerThreadExecutor implements Executor {

    // Runs every task immediately, on the thread that submits it.
    // Handy in unit tests, where you want background code to run synchronously.
    @Override
    public void execute(Runnable task) {
        task.run();
    }

    public static void main(String[] args) {
        Executor executor = new CallerThreadExecutor();
        String caller = Thread.currentThread().getName();

        executor.execute(() -> {
            boolean sameThread = Thread.currentThread().getName().equals(caller);
            System.out.println("Invoice PDF generated; ran on caller thread: " + sameThread);
        });
        System.out.println("execute() returned after the task finished");
    }
}
Output
Invoice PDF generated; ran on caller thread: true
execute() returned after the task finished

How the code works

  1. execute() simply calls task.run(), so the task runs on the thread that called execute().
  2. Because of that, execute() returns only after the task has finished, and the two lines always print in the same order.
  3. Code written against the Executor type cannot tell this apart from a real thread pool, which is exactly what makes it a good test double.

5. Example: Decorating Another Executor

Because Executor is so small, it is easy to wrap. This decorator numbers every task and logs when it starts and ends, then hands the work to a real executor.

AuditedExecutor.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class AuditedExecutor implements Executor {

    private final Executor delegate;
    private final AtomicInteger submitted = new AtomicInteger();

    AuditedExecutor(Executor delegate) {
        this.delegate = delegate;
    }

    // Decorates another Executor: numbers each task before handing it over
    @Override
    public void execute(Runnable task) {
        int id = submitted.incrementAndGet();
        delegate.execute(() -> {
            System.out.println("[task " + id + "] start");
            task.run();
            System.out.println("[task " + id + "] end");
        });
    }

    int submittedCount() {
        return submitted.get();
    }

    public static void main(String[] args) {
        AuditedExecutor audited;
        try (ExecutorService worker = Executors.newSingleThreadExecutor()) {
            audited = new AuditedExecutor(worker);
            audited.execute(() -> System.out.println("  resize product images"));
            audited.execute(() -> System.out.println("  rebuild search index"));
        } // close() waits for both tasks
        System.out.println("Tasks handed over: " + audited.submittedCount());
    }
}
Output
[task 1] start
  resize product images
[task 1] end
[task 2] start
  rebuild search index
[task 2] end
Tasks handed over: 2

How the code works

  1. AuditedExecutor implements Executor and keeps a reference to a delegate executor.
  2. execute() wraps the original task in a new Runnable that prints the start and end markers around task.run().
  3. An AtomicInteger counts tasks safely, even if several threads call execute() at once.
  4. The delegate is a single-thread ExecutorService; closing it in try-with-resources waits for both tasks before the count is printed.

6. Executor vs ExecutorService

NeedUse
Run fire-and-forget tasksExecutor
Get a result or an exception backExecutorService.submit()
Run a batch of tasksinvokeAll() / invokeAny()
Shut the threads down cleanlyshutdown(), close()

Accepting an Executor parameter keeps your own classes flexible: callers can pass a pool, a virtual-thread executor or a test executor. Most applications still create an ExecutorService, because they need results and a way to shut down.

7. Common Mistakes and Best Practices

  • Assuming execute() is asynchronous. The contract allows the task to run on the calling thread, as the first example shows.
  • Expecting results. execute() returns void; use ExecutorService.submit() when you need a Future.
  • Losing exceptions. With a thread pool, an exception thrown from an executed task goes to the worker thread's uncaught exception handler.
  • Depend on the interface. Accept Executor in constructors instead of creating threads inside your classes; it makes code easier to test.

8. Summary

  • Executor has one method, execute(Runnable), and is the root of the Executor Framework.
  • It separates submitting a task from deciding which thread runs it.
  • An implementation may run the task on a new thread, a pooled thread or the calling thread.
  • Small custom executors are useful for tests and for decorating other executors; use ExecutorService when you need results or lifecycle control.

Related Tutorials

9. References