CodeBlanks Logo Icon CodeBlanks

ExecutorService

Learn thread pools with ExecutorService.

ExecutorService

ExecutorService is the interface that manages a thread pool. Executors.newSingleThreadExecutor() gives a single-thread pool, newFixedThreadPool(n) gives an n-thread pool.

ExecutorService pool =
    Executors.newSingleThreadExecutor();
pool.submit(() -> System.out.println("Task"));
pool.shutdown();

Instead of starting tasks yourself with new Thread().start(), you submit them to a pool. The pool reuses threads and lowers overhead. When done, close the pool with shutdown(). This is the preferred approach in production code.

submit and Runnable

submit() takes a Runnable and returns a Future. The task is handed to the pool; you track its status via the Future.

Future<?> f = pool.submit(() -> {
    System.out.println("Running");
});
f.get();  // wait until done

Future.get() blocks the caller until the task finishes. This guarantees specific output orders. If the task throws, you get it wrapped in ExecutionException. This control makes concurrent code easier to read.

Practice Run a task with ExecutorService

Write a main method in a PoolDemo class; create a pool with Executors.newSingleThreadExecutor(). Submit a task with pool.submit(() -> 2 + 3) (result is a Future<Integer>). Wait for the result with f.get() and print it with System.out.println. Finally call pool.shutdown().

Starter code

Main.java
import java.util.concurrent.*;

// Write main in PoolDemo

// Create a pool with newSingleThreadExecutor

// Submit a task returning 2+3; print get; call shutdown

Sample solution

Main.java
import java.util.concurrent.*;

class PoolDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<Integer> f = pool.submit(() -> 2 + 3);
        System.out.println(f.get());
        pool.shutdown();
    }
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is an ExecutorService shut down?

  • shutdown() Correct answer
  • close()
  • terminate()
  • stop()

Explanation: shutdown() closes the pool gracefully.

2 Complete the submit call

Question
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> f = pool.____(() -> System.out.println("Görev"));
Answer
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> f = pool.submit(() -> System.out.println("Görev"));

Explanation: submit() takes a Runnable and returns a Future.

3 Match ExecutorService methods

Term Meaning
submit() Submits a task to the pool
shutdown() Closes the pool
newSingleThreadExecutor() Single-thread pool
newFixedThreadPool(n) n-thread pool

All lessons in Advanced