Executor Interface in Java: The Root of the Executor Framework
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
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
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 withsubmit(), bulk execution and lifecycle methods such asshutdown()andclose().ScheduledExecutorService(interface): Extends ExecutorService with delayed and periodic execution.AbstractExecutorService(abstract class): Implementssubmit(),invokeAll()andinvokeAny()on top ofexecute().ThreadPoolExecutor and ForkJoinPool(classes): The JDK's main concrete executors; both ultimately implementExecutor.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.
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");
}
}
Invoice PDF generated; ran on caller thread: true execute() returned after the task finished
How the code works
execute()simply callstask.run(), so the task runs on the thread that calledexecute().- Because of that,
execute()returns only after the task has finished, and the two lines always print in the same order. - Code written against the
Executortype 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.
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());
}
}
[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
AuditedExecutorimplementsExecutorand keeps a reference to adelegateexecutor.execute()wraps the original task in a newRunnablethat prints the start and end markers aroundtask.run().- An
AtomicIntegercounts tasks safely, even if several threads callexecute()at once. - 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
| Need | Use |
|---|---|
| Run fire-and-forget tasks | Executor |
| Get a result or an exception back | ExecutorService.submit() |
| Run a batch of tasks | invokeAll() / invokeAny() |
| Shut the threads down cleanly | shutdown(), 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()returnsvoid; useExecutorService.submit()when you need aFuture. - 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
Executorin constructors instead of creating threads inside your classes; it makes code easier to test.
8. Summary
Executorhas 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
ExecutorServicewhen you need results or lifecycle control.
Related Tutorials
9. References
Frequently Asked Questions (FAQ)
Q1. Does Executor.execute() always start a new thread?
No. The contract only says the task runs at some time in the future. An implementation may use a new thread, a pooled thread or the calling thread itself.
Q2. What is the difference between Executor and ExecutorService?
Executor only runs tasks. ExecutorService extends it with submit(), which returns a Future, bulk methods such as invokeAll(), and lifecycle methods such as shutdown(), awaitTermination() and close().
Q3. What exceptions can execute() throw?
It throws RejectedExecutionException when the task cannot be accepted, for example after the executor has been shut down, and NullPointerException when the task is null.
Q4. Can I pass a Callable to Executor.execute()?
No. execute() takes a Runnable. Submit a Callable to an ExecutorService, or wrap it in a FutureTask, which is a Runnable, and pass that to execute().
Q5. Do I need to shut down an Executor?
The Executor interface has no shutdown method. If the object is actually an ExecutorService, such as a thread pool, shut it down through that interface or use try-with-resources so its threads do not keep running.