Concurrency & Executors
concurrency & executors beyond raw threads, java provides a rich concurrency toolkit: executors, completablefuture, locks, concurrent collections and (java 21+) structured concurrency.
Introduction
Beyond raw threads, Java provides a rich concurrency toolkit: Executors, CompletableFuture, locks, concurrent collections and (Java 21+) structured concurrency.
Informative example
CompletableFuture — async pipelines without callback hell:
import java.util.concurrent.*;CompletableFuture<String> user = CompletableFuture.supplyAsync(() -> fetchUser(42));CompletableFuture<String> perms = CompletableFuture.supplyAsync(() -> fetchPerms(42));user.thenCombine(perms, (u, p) -> u + " has " + p).thenAccept(System.out::println).exceptionally(ex -> { System.err.println(ex); return null; });
Real-world use
At Netflix, almost every microservice composes 10-30 downstream calls per request. CompletableFuture (or Reactor on top of it) is what stitches them together so the page returns in 200 ms instead of 2 s of serial waits.
Best practices
- Always supply your own Executor to async methods — the default ForkJoinPool is small.
- Use
ConcurrentHashMap, neverCollections.synchronizedMap. - Time-box async calls with
.orTimeout(2, SECONDS).
Purpose of this lesson
Master Concurrency & Executors so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Concurrency & Executors.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Submit task
<code>executor.submit(Callable)</code> returns a <code>Future</code>.
Debugging tips
RejectedExecutionException→ queue is full or executor is shut down.- Use
CompletableFuture+thenApplychains instead of blocking.get().
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Concurrency & Executors daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Concurrency & Executors in one minute.
Q2When would you avoid Concurrency & Executors?
Summary
In this lesson you learned Concurrency & Executors — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.