Java
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.
Exercise 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().
Show example solution
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();
}
}
Test yourself
-
How is an ExecutorService shut down?
- shutdown()
- close()
- terminate()
- stop()
Show answer
shutdown() — shutdown() closes the pool gracefully.
-
Complete the submit call
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> f = pool.____(() -> System.out.println("Görev"));
Show answer
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> f = pool.submit(() -> System.out.println("Görev"));
-
Match ExecutorService methods
- submit()
- Submits a task to the pool
- shutdown()
- Closes the pool
- newSingleThreadExecutor()
- Single-thread pool
- newFixedThreadPool(n)
- n-thread pool
Next lesson: Callable and Future