QUICK REFERENCE

Concurrency Cheat Sheet

Mastering threads, locks, and synchronization patterns for high-performance systems.

Producer Bounded BufferConsumer
Synchronization

Mutex / Lock

Mutually Exclusive lock. Only one thread can hold the lock at a time. Used to protect critical sections.

Lock lock = new ReentrantLock();
void safeMethod() {
lock.lock();
try {
// Critical section
balance++;
} finally {
lock.unlock();
}
}
Synchronization

Semaphore

Controls access to a resource with a counter. Allows up to N threads to access simultaneously.

Semaphore sem = new Semaphore(3); // 3 permits
void accessResource() {
try {
sem.acquire(); // Decrements count
// Use resource
} catch (InterruptedException e) { ... }
finally {
sem.release(); // Increments count
}
}
Pattern

Producer-Consumer

Decouples processes that produce data from those that consume it using a shared buffer (queue).

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// Producer
queue.put(1);
// Consumer
int val = queue.take(); // Blocks if empty
Performance

Thread Pool

Reuses a pool of worker threads to execute tasks, avoiding the overhead of creating new threads for every task.

ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> {
System.out.println("Task executed");
});
Anti-Pattern

Deadlock

A situation where two or more threads are blocked forever, waiting for each other to release resources.

// Thread 1: Lock A -> Wait B
// Thread 2: Lock B -> Wait A
// Result: Freeze.
// Fix: Acquire locks in the same order everywhere.
synchronized(A) { synchronized(B) { ... } }
Synchronization

Atomic Variables

Thread-safe variables that support lock-free thread-safe operations on single variables.

AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet(); // Thread-safe ++
count.addAndGet(5);
Synchronization

Read-Write Lock

Allows multiple readers simultaneously or one writer. Optimized for read-heavy situations.

ReadWriteLock rwLock = new ReentrantReadWriteLock();
// Multiple threads can hold this
rwLock.readLock().lock();
// Only one thread can hold this
rwLock.writeLock().lock();
Async

Future / Promise

A placeholder object for a result that will be available in the future.

Future<String> future = executor.submit(() -> "Result");
// Do other work...
String result = future.get(); // Blocking wait