Understanding Concurrency Fundamentals

1. Creating Threads

ApproachCode
Runnablenew Thread(() -> ...).start()
Subclassclass T extends Thread { run() }
BuilderThread.ofPlatform().name("w").start(r)
VirtualThread.startVirtualThread(r) (Java 21+)

2. Understanding Thread States

StateMeaning
NEWCreated, not started
RUNNABLEEligible to run
BLOCKEDWaiting for monitor lock
WAITINGIndefinite wait (wait, join, park)
TIMED_WAITINGBounded wait (sleep, join(ms))
TERMINATEDRun completed

3. Understanding Thread Safety

StrategyUse
ImmutabilityFinal fields, no mutators
ConfinementOne thread per object
Synchronizationsynchronized, locks
Atomics/VarHandleLock-free
Thread-safe libsConcurrent collections

4. Using synchronized Keyword

FormLock Object
Instance methodthis
Static methodClass object
BlockExplicit object
VisibilityEstablishes happens-before
ReentrantSame thread can re-enter

5. Understanding Volatile Keyword

GuaranteesDetail
VisibilityReads see latest write
OrderingNo reordering across volatile
AtomicityReference/long/double atomic write
NotCompound ops (i++) — use Atomic

6. Using wait() and notify() (Object methods)

MethodEffect
wait()Release lock + wait
notify()Wake one waiter
notifyAll()Wake all waiters
RequiredHold monitor (synchronized)
Patternwhile (!cond) wait();
Warning: Always check condition in while loop — spurious wakeups occur.

7. Understanding Thread Interruption

APIEffect
thread.interrupt()Set flag, wake from blocking ops
Thread.interrupted()Check + clear (static)
isInterrupted()Check, no clear
Blocking opsThrow InterruptedException + clear flag

8. Using Thread.join() (waiting for completion)

FormUse
join()Wait indefinitely
join(ms)Timeout
join(ms, ns)Nanoseconds
ThrowsInterruptedException

9. Understanding ThreadLocal Variables

APIUse
ThreadLocal.withInitial(Supplier)Lazy init per thread
get / set / removeCRUD
InheritableThreadLocalChild threads inherit
PitfallMemory leak in pools — always remove()
ModernScopedValue (Java 21+ preview)

10. Understanding Memory Consistency Errors

ConceptDetail
Happens-beforePartial order across threads
Sourcessynchronized, volatile, Thread.start/join, Atomic
Without HBReads may see stale values
JMMJava Memory Model defines guarantees

11. Setting Thread Priority (setPriority)

ConstantValue
MIN_PRIORITY1
NORM_PRIORITY5 (default)
MAX_PRIORITY10
EffectOS hint only — not guaranteed

12. Using Daemon Threads (setDaemon)

PropertyEffect
setDaemon(true)JVM exits when only daemons remain
Set beforestart() only
InheritsFrom creating thread
UseBackground tasks (timers, GC threads)