Skip to content

Instantly share code, notes, and snippets.

@CrypticMessenger
Created January 18, 2026 10:19
Show Gist options
  • Select an option

  • Save CrypticMessenger/63051f784a13a1a28edeb73007e99193 to your computer and use it in GitHub Desktop.

Select an option

Save CrypticMessenger/63051f784a13a1a28edeb73007e99193 to your computer and use it in GitHub Desktop.
Primitive / Concept What is it? Why use it? (The Problem) Where to use? (Use-Cases) Key Notes & Trade-offs
Volatile Keyword Lightweight synchronization that guarantees visibility (reads/writes go directly to main memory). Prevents threads from reading stale data from CPU caches and prevents instruction reordering by the compiler. Status Flags: Simple boolean signals like shutdownRequested to stop a task. Does not guarantee atomicity. Operations like count++ are still unsafe.
Atomics Non-blocking wrapper classes (AtomicInteger, AtomicReference) using hardware CAS (Compare-And-Swap). Solves Read-Modify-Write race conditions (like count++) without the overhead of putting threads to sleep. Counters & Accumulators: Request counters, High Score trackers, or updating a single variable based on its previous value. Faster than locks for single variables, but difficult to manage invariants involving multiple variables.
ThreadLocal Thread-confinement. A specific storage area where every thread gets its own independent copy of an object. Avoids synchronization entirely by not sharing. Also avoids passing "context" parameters through deep call stacks. Per-Thread Instances: Non-thread-safe objects like SimpleDateFormat.
Context Passing: Carrying User ID or Transaction ID through layers.
Crucial: You must call .remove() in a finally block to prevent memory leaks, especially in thread pools (Tomcat/Jetty).
Synchronized Intrinsic locking (Mutex) that enforces Mutual Exclusion. Only one thread enters at a time. Solves Check-Then-Act race conditions. Guarantees both Atomicity (compound actions act as one) and Visibility. Compound Actions: Lazy Initialization (checking null then creating), or protecting critical sections (adding to a shared List). Performance can suffer if the scope is too wide. Keep synchronized blocks short.
Reentrancy (Bonus Concept) The ability for a thread to acquire a lock it already holds. Lock ownership is per-thread, not per-invocation. Prevents Deadlocks in Object-Oriented programming when a synchronized method calls a synchronized super() method. Inheritance: Overriding synchronized methods in child classes that call the parent implementation. Without this, standard OO patterns in Java would instantly freeze the application.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment