Concurrency
7 pages · ~5 min✓ Reviewed
Builds on JVM and Memory. Next up: Modern Java Features.
Threads and Runnable Mental Model
1. Thread, Task, Worker
- A thread = independent path of execution
- Shared: the process heap
- Own: stack + program counter
| Role | Result | |
|---|---|---|
| Runnable | describes the task: void run() | nothing |
| Callable<V> | task: V call() | a value; may throw checked |
| Thread | the worker that runs it | - |
2. start() vs run()
start()creates a new thread that callsrun()run()called directly = plain call on the current thread
java
Runnable r = () -> System.out.println(
Thread.currentThread().getName());
Thread t = new Thread(r);
t.start(); t.join();
r.run();output
Thread-0
main3. Thread States
- NEW
- RUNNABLE
- BLOCKEDWAITING, TIMED_WAITING
- TERMINATED
ExecutorService and Thread Pools
1. Submit and Factories
submit(task)→ Future;execute(task)→ nothingget()blocks; task errors wrapped in ExecutionExceptionget(timeout, unit)→ TimeoutException
| Factory | Threads |
|---|---|
newFixedThreadPool(n) | n threads, unbounded queue |
newCachedThreadPool() | unbounded threads |
newSingleThreadExecutor() | one thread |
newVirtualThreadPerTaskExecutor() |
synchronized and volatile
1. synchronized: the monitor
- Mutual exclusion: one thread holds the object's monitor
- Visibility: unlock publishes writes to the next acquirer
- Prefer a
private finallock object overthis
| Form | Locks |
|---|---|
| Instance method | this |
| Static method | the Class object |
| Block | any object you pick |
2. volatile
Locks and Atomic Classes
1. ReentrantLock
- Explicit lock() and unlock(); always unlock in
finally - Reentrant: the same thread may re-acquire it
java
lock.lock(); try { count++; } finally { lock.unlock(); }
| synchronized | ReentrantLock | |
|---|---|---|
| Timeout | no | tryLock(timeout) |
| Interrupt | no | lockInterruptibly() |
| Fair order | no |
ConcurrentHashMap and CompletableFuture
1. ConcurrentHashMap
- Lock-free reads; writes lock one bin, CAS on empty bins
- No null keys or values
- Use atomic
putIfAbsent,computeIfAbsent,merge - get then put on separate calls = race
java
counts.merge(word, 1, Integer::sum);| Map | Lock | Iterator |
|---|---|---|
| ConcurrentHashMap | per bin | weakly consistent, no CME |
| synchronizedMap | one lock, every call |
Concurrency Pitfalls and Cheat Sheet
1. Races and Deadlock
- Race: unsynchronized check-then-act or read-modify-write
- Fix: atomics, locks or concurrent collections
- Deadlock needs circular wait on locks
- Prevent: fixed global lock order, or
tryLockwith timeout
2. Interrupts and Confinement
- Never swallow
InterruptedException: restore the flag or rethrow
java
try { task = queue.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
- Prefer immutability and thread confinement
Check yourself
Two threads each run count++ 1000 times on a volatile int count. Is the final value always 2000?
- No, it is often less than 2000.
volatilegives visibility, not atomicity:count++is read, add, write.- Fix:
AtomicInteger.incrementAndGet().
A pool has core=2, max=4 and an ArrayBlockingQueue of 10. You submit 5 tasks at once. How many threads run?
- Two. Tasks 3 to 5 wait in the queue.
- A third thread appears only once the queue is full.
On a ConcurrentHashMap: if (!map.containsKey(k)) map.put(k, 1); What is wrong?
- Each call is atomic, but the pair is not: two threads can both see k absent.
- Fix:
map.merge(k, 1, Integer::sum)orputIfAbsent.