Understanding Concurrency Fundamentals
1. Creating Threads
| Approach | Code |
| Runnable | new Thread(() -> ...).start() |
| Subclass | class T extends Thread { run() } |
| Builder | Thread.ofPlatform().name("w").start(r) |
| Virtual | Thread.startVirtualThread(r) (Java 21+) |
2. Understanding Thread States
| State | Meaning |
| NEW | Created, not started |
| RUNNABLE | Eligible to run |
| BLOCKED | Waiting for monitor lock |
| WAITING | Indefinite wait (wait, join, park) |
| TIMED_WAITING | Bounded wait (sleep, join(ms)) |
| TERMINATED | Run completed |
3. Understanding Thread Safety
| Strategy | Use |
| Immutability | Final fields, no mutators |
| Confinement | One thread per object |
| Synchronization | synchronized, locks |
| Atomics/VarHandle | Lock-free |
| Thread-safe libs | Concurrent collections |
4. Using synchronized Keyword
| Form | Lock Object |
| Instance method | this |
| Static method | Class object |
| Block | Explicit object |
| Visibility | Establishes happens-before |
| Reentrant | Same thread can re-enter |
5. Understanding Volatile Keyword
| Guarantees | Detail |
| Visibility | Reads see latest write |
| Ordering | No reordering across volatile |
| Atomicity | Reference/long/double atomic write |
| Not | Compound ops (i++) — use Atomic |
6. Using wait() and notify() (Object methods)
| Method | Effect |
wait() | Release lock + wait |
notify() | Wake one waiter |
notifyAll() | Wake all waiters |
| Required | Hold monitor (synchronized) |
| Pattern | while (!cond) wait(); |
Warning: Always check condition in while loop — spurious wakeups occur.
7. Understanding Thread Interruption
| API | Effect |
thread.interrupt() | Set flag, wake from blocking ops |
Thread.interrupted() | Check + clear (static) |
isInterrupted() | Check, no clear |
| Blocking ops | Throw InterruptedException + clear flag |
8. Using Thread.join() (waiting for completion)
| Form | Use |
join() | Wait indefinitely |
join(ms) | Timeout |
join(ms, ns) | Nanoseconds |
| Throws | InterruptedException |
9. Understanding ThreadLocal Variables
| API | Use |
ThreadLocal.withInitial(Supplier) | Lazy init per thread |
get / set / remove | CRUD |
InheritableThreadLocal | Child threads inherit |
| Pitfall | Memory leak in pools — always remove() |
| Modern | ScopedValue (Java 21+ preview) |
10. Understanding Memory Consistency Errors
| Concept | Detail |
| Happens-before | Partial order across threads |
| Sources | synchronized, volatile, Thread.start/join, Atomic |
| Without HB | Reads may see stale values |
| JMM | Java Memory Model defines guarantees |
11. Setting Thread Priority (setPriority)
| Constant | Value |
| MIN_PRIORITY | 1 |
| NORM_PRIORITY | 5 (default) |
| MAX_PRIORITY | 10 |
| Effect | OS hint only — not guaranteed |
12. Using Daemon Threads (setDaemon)
| Property | Effect |
setDaemon(true) | JVM exits when only daemons remain |
| Set before | start() only |
| Inherits | From creating thread |
| Use | Background tasks (timers, GC threads) |