newSingleThreadExecutor: Sequential Task Execution
What you'll learn: How newSingleThreadExecutor guarantees strict sequential execution of tasks using a single worker thread.
The Sequential Execution Guarantee
Executors.newSingleThreadExecutor() creates an executor with exactly one worker thread backed by an unbounded queue. This design ensures that submitted tasks execute one at a time, in the order they were submitted (FIFO), never concurrently.
Think of it like a single-lane bridge: only one car can cross at a time, and all other cars must wait in line. No matter how many tasks you submit, they'll execute sequentially on that one thread.
How It Works
When you submit tasks:
- The single worker thread picks up the first task from the queue
- Executes it completely to completion
- Only then picks up the next task
- Continues until the queue is empty
The unbounded queue means tasks will never be rejected due to queue capacity—they'll just wait their turn.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Task 1: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 2: " + Thread.currentThread().getName()));
executor.execute(() -> System.out.println("Task 3: " + Thread.currentThread().getName()));
executor.shutdown();
All three tasks run on the same thread, one after another—never overlapping.
When to Use It
Perfect for scenarios requiring strict ordering:
- Event logging where sequence matters
- Processing messages that must maintain order
- State machines where each transition must complete before the next
Unlike calling methods directly on the current thread, this approach offloads work to a background thread while maintaining sequential guarantees.
Key Takeaway: newSingleThreadExecutor provides thread-safe sequential execution with zero concurrency—ideal when task order matters and you want background processing without manual synchronization concerns.