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; }
}
| Tool | Use |
|---|---|
synchronized | Intrinsic lock on an object or method |
volatile | Visibility of a variable across threads (not atomicity) |
java.util.concurrent.atomic | Lock-free counters (AtomicInteger) |
ReentrantLock | Explicit locks, try-lock, fairness |
| Concurrent collections | ConcurrentHashMap, 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
| Problem | Meaning |
|---|---|
| Race condition | Outcome depends on timing |
| Deadlock | Threads wait on each other's locks forever |
| Starvation | A thread never gets the resource |
| Visibility bug | One 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.
Loading Comments...