Java concurrency basics: threads, ExecutorService and thread-safe code
Why shared mutable state breaks under threads, using ExecutorService and Future instead of raw threads, synchronized, atomic variables, ConcurrentHashMap and CompletableFuture.
Threads let a program do several things at once: serve many requests, or keep the UI responsive while work happens in the background. They also introduce bugs that only appear under load.
The problem: shared mutable state
class Counter {
private int count = 0;
void increment() { count++; } // read, add, write: three steps
}Run increment() a million times from four threads and the result is usually less than four
million: two threads read the same value and one update is lost. This is a race condition.
The three ways out, in order of preference:
- Don't share: give each thread its own data and combine results at the end.
- Don't mutate: share only immutable objects.
- Synchronise access: locks, atomics or concurrent collections.
Use an ExecutorService, not raw threads
ExecutorService pool = Executors.newFixedThreadPool(4);
try {
List<Future<Integer>> results = new ArrayList<>();
for (String route : routes) {
results.add(pool.submit(() -> priceRoute(route))); // Callable<Integer>
}
int total = 0;
for (Future<Integer> f : results) {
total += f.get(); // waits; rethrows the task's exception wrapped
}
} finally {
pool.shutdown();
}The pool reuses a fixed number of threads, queues the rest, and gives you each result as a
Future. Always shutdown() the executor, or the JVM may never exit.
Making shared state safe
// 1. synchronized: one thread at a time in this method
synchronized void increment() { count++; }
// 2. atomics: lock-free for single variables
private final AtomicInteger count = new AtomicInteger();
void increment() { count.incrementAndGet(); }
// 3. concurrent collections
ConcurrentHashMap<String, Integer> seatsSold = new ConcurrentHashMap<>();
seatsSold.merge("EI-123", 1, Integer::sum); // atomic per keyNever use a plain HashMap from several threads, even if "only one thread writes": readers can see
it half-updated.
CompletableFuture: composing async work
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> basePrice(route), pool);
CompletableFuture<Integer> fees = CompletableFuture.supplyAsync(() -> airportFees(route), pool);
int total = price.thenCombine(fees, Integer::sum)
.orTimeout(2, TimeUnit.SECONDS)
.join();thenApply, thenCombine and exceptionally chain steps without blocking in between.
Deadlocks
If thread A holds lock 1 and waits for lock 2 while thread B holds lock 2 and waits for lock 1, both wait forever. Avoid it by always acquiring locks in the same order, holding them briefly, and never calling unknown code while holding a lock.
Common mistakes
- Forgetting
shutdown()on executors. count++orcheck-then-act(if (!map.containsKey(k)) map.put(k, v)) on shared data: useputIfAbsentorcomputeIfAbsent.- Ignoring the exception inside a
Future:get()wraps it inExecutionException.
Concurrency is a module of Java Advanced.
Questions and answers
- Should I create threads directly with new Thread() in Java?
- Rarely. An ExecutorService manages a pool of threads, reuses them, queues tasks and lets you collect results through Futures. Creating threads by hand makes it easy to create too many and hard to shut them down cleanly.
- Is count++ thread-safe in Java?
- No. count++ reads, adds and writes in three steps, so two threads can read the same value and one update is lost. Use an AtomicInteger, a synchronized block, or avoid sharing the counter.
Practise it
Read next
- Java exceptions: checked vs unchecked, try-with-resources and error messages
When Java forces you to handle an exception and when it doesn't, how try-with-resources closes files for you, writing your own exceptions, and the mistakes that hide real bugs.
- Java streams and lambdas: filter, map, collect and groupingBy
Lambdas and method references, the stream pipeline, collecting into lists and maps, groupingBy for reports, Optional, and when a plain loop is clearer.