Skip to main content

Concurrency in Java

Threads​

Thread t = new Thread(() -> System.out.println("running in " + Thread.currentThread().getName()));
t.start();
t.join(); // wait for it to finish

Shared state needs protection​

class Counter {
private int value;

public synchronized void increment() { value++; } // mutual exclusion
public synchronized int get() { return value; }
}
ToolUse
synchronizedIntrinsic lock on an object or method
volatileVisibility of a variable across threads (not atomicity)
java.util.concurrent.atomicLock-free counters (AtomicInteger)
ReentrantLockExplicit locks, try-lock, fairness
Concurrent collectionsConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue

Executors​

Do not create threads by hand in production code; use a pool.

import java.util.concurrent.*;

ExecutorService pool = Executors.newFixedThreadPool(4);

Future<Integer> result = pool.submit(() -> {
Thread.sleep(200);
return 42;
});

System.out.println(result.get()); // blocks until ready
pool.shutdown();

CompletableFuture​

CompletableFuture<String> greeting = CompletableFuture
.supplyAsync(() -> "Hello")
.thenApply(s -> s + ", PrepVerse")
.exceptionally(ex -> "fallback");

System.out.println(greeting.join());

Common pitfalls​

ProblemMeaning
Race conditionOutcome depends on timing
DeadlockThreads wait on each other's locks forever
StarvationA thread never gets the resource
Visibility bugOne thread does not see another's write
NOTE

Java 21 introduced virtual threads (Thread.ofVirtual()), lightweight threads that make blocking-style code scale to very many concurrent tasks.