ExecutorService: submit and execute
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)An ExecutorService accepts work in two ways: execute(task) only runs it, while submit(task) also hands back a Future that tracks the task. The kind of pool you create, fixed, single-thread or cached, decides how many threads run that work.
execute() versus submit()
ExecutorService runs submitted tasks on a pool of threads and manages their life cycle, including shutting the pool down.
execute(task) runs a task and returns nothing. submit(task) also returns a Future, an object that stands for a task whose result will be ready later.
Example 1 · execute and submit side by side
import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class ExecuteVersusSubmitDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService pool = Executors.newFixedThreadPool(1);
pool.execute(() -> System.out.println("execute: printing bus pass")); Future<?> receipt = pool.submit(() -> System.out.println("submit: printing library card"));
Object result = receipt.get(); // waits until the task has finished System.out.println("Done? " + receipt.isDone() + ", result = " + result);
pool.shutdown(); }}execute: printing bus pass submit: printing library card Done? true, result = null
What this code does
executereturns nothing, so main cannot ask about that task later.submitreturns aFuture<?>, a receipt for the task.receipt.get()blocks main until the task has run. ARunnablehas no result, soget()returnsnull, andisDone()is nowtrue.
execute(Runnable) is the one method of the small parent interface Executor. submit(task) comes from ExecutorService and accepts a Runnable or a Callable.
With a Future you can ask isDone(), or call get() to wait until the task has finished. For a Runnable, get() returns null, because the task has no result; it is still useful for waiting and, as the last section shows, for seeing errors. Callable and the rest of Future are covered in the next lesson. For now, think of execute as "fire and forget" and submit as "give me a receipt".
Fixed, single and cached pools
The Executors class has a factory method for each common kind of pool. They differ in how many threads they create and what happens when tasks pile up.
Example 2 · A single-thread executor keeps a UPI ledger in order
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
class Wallet { private int balance = 0; // touched only by the one ledger thread
void apply(String what, int amount) { balance += amount; System.out.println(what + " " + amount + " -> balance " + balance); }}
public class LedgerDemo { public static void main(String[] args) throws InterruptedException { Wallet wallet = new Wallet(); ExecutorService ledger = Executors.newSingleThreadExecutor();
ledger.submit(() -> wallet.apply("Add money", 1000)); ledger.submit(() -> wallet.apply("Pay subscription", -120)); ledger.submit(() -> wallet.apply("Pay hostel fee", -800)); ledger.submit(() -> wallet.apply("Refund", 50));
ledger.shutdown(); ledger.awaitTermination(5, TimeUnit.SECONDS); }}Add money 1000 -> balance 1000 Pay subscription -120 -> balance 880 Pay hostel fee -800 -> balance 80 Refund 50 -> balance 130
What this code does
- One thread runs the tasks strictly in submission order, so the balance never goes negative by running "Pay hostel fee" before "Add money".
- Because only that one thread ever touches
balance,Walletneeds nosynchronizedhere. This "one thread owns the data" idea is a simple way to avoid races.
Example 3 · A cached pool creates threads, then reuses them
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class CachedPoolDemo { static final Set<String> names = new HashSet<>();
static void slowTask() { synchronized (names) { names.add(Thread.currentThread().getName()); } try { Thread.sleep(50); // all 5 tasks overlap } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static void runBatch(ExecutorService pool) throws Exception { List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { futures.add(pool.submit(CachedPoolDemo::slowTask)); } for (Future<?> f : futures) { f.get(); // wait for the whole batch } }
public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newCachedThreadPool();
runBatch(pool); System.out.println("After batch 1: " + names.size() + " threads");
Thread.sleep(100); // the 5 threads are idle now runBatch(pool); System.out.println("After batch 2: " + names.size() + " threads");
pool.shutdown(); }}After batch 1: 5 threads After batch 2: 5 threads
What this code does
- In batch 1 no thread is free when each task arrives, so the cached pool creates a new thread for every task: 5 threads.
- In batch 2 the same 5 threads are idle and waiting, so they take the new tasks and no sixth thread appears. With 500 slow tasks at once, the pool would create 500 threads.
newFixedThreadPool(n): exactlynthreads at most, and a queue with no size limit. Good for a steady load whose size you know.newSingleThreadExecutor(): one thread, so tasks run one at a time in the order they were submitted. Good for work that must stay in order, such as writing a ledger or a log file.newCachedThreadPool(): no fixed size. A new task goes to an idle thread if there is one; otherwise a new thread is created. Threads that stay idle for 60 seconds are removed.- The cached pool has no upper limit on threads. Fine for many short tasks, dangerous for a flood of slow ones (see "Choose a pool size").
Pool thread names in the output
Threads made by the Executors factory methods are named pool-N-thread-M. N counts the pools created in this program so far, starting at 1, and M counts the threads that pool has created.
Example 4 · Reading pool thread names
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;
public class PoolNamesDemo { static void showName(ExecutorService pool, String label) throws Exception { pool.submit(() -> System.out.println(label + " -> " + Thread.currentThread().getName())) .get(); }
public static void main(String[] args) throws Exception { Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println(" " + t.getName() + " died: " + e.getMessage()));
ExecutorService fixed = Executors.newFixedThreadPool(2); ExecutorService single = Executors.newSingleThreadExecutor(); ExecutorService cached = Executors.newCachedThreadPool();
showName(fixed, "fixed "); showName(single, "single"); showName(cached, "cached");
single.execute(() -> { throw new IllegalStateException("printer jammed"); }); Thread.sleep(100); // let the failing task finish showName(single, "single after the crash");
fixed.shutdown(); single.shutdown(); cached.shutdown(); }}fixed -> pool-1-thread-1 single -> pool-2-thread-1 cached -> pool-3-thread-1 pool-2-thread-1 died: printer jammed single after the crash -> pool-2-thread-2
What this code does
- Each factory call creates a new pool, so the pool number goes 1, 2, 3 in creation order. Each pool's first thread is
thread-1. - The task given with
executethrew, sopool-2-thread-1died and the handler set withsetDefaultUncaughtExceptionHandlerprinted its message. The single-thread pool replaced it withpool-2-thread-2. Without that handler, the default one prints a full stack trace toSystem.err.
These names make output and error messages readable. pool-2-thread-1 is the first thread of the second pool. If you see pool-2-thread-2 in a pool that has only one thread, the first thread has died and the pool has replaced it. The most common reason for that is a task, given with execute, that threw an exception. The exception ends the worker thread, just as it would end a thread you started yourself, and the pool starts a new one for the next task.
Exceptions hidden inside submit()
When a task given to submit throws an exception, the pool catches it and stores it inside the Future. Nothing is printed.
Example 5 · A failed task that nobody notices
import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class HiddenExceptionDemo { static void averageMarks(int total, int students) { int avg = total / students; // students = 0 -> ArithmeticException System.out.println("Average: " + avg); }
public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(2);
Future<?> report = pool.submit(() -> averageMarks(450, 0)); Thread.sleep(100); System.out.println("Submitted. Task finished? " + report.isDone()); System.out.println("No error printed so far.");
try { report.get(); } catch (ExecutionException e) { System.out.println("get() reveals: " + e.getCause()); } pool.shutdown(); }}Submitted. Task finished? true No error printed so far. get() reveals: java.lang.ArithmeticException: / by zero
What this code does
- The task crashed with a division by zero, but nothing appeared on the screen:
submitcaught the exception and stored it in theFuture.isDone()istrueeven though the task failed. get()throws anExecutionExceptionwhosegetCause()is the realArithmeticException. Remove thetryblock and this error is never seen.
The exception comes out only when someone calls get(), wrapped in an ExecutionException. If nobody calls get(), the error is lost without a trace.
A task given to execute behaves differently: the exception escapes, the worker thread ends, and the thread's uncaught exception handler prints the stack trace to System.err. So with submit, always do one of two things: call get() on the Future and handle ExecutionException, or catch and log exceptions inside the task itself.
Future nobody checked.Next step
Check your understanding
12 quick questions