CONCURRENCY CONTROLS

Synchronization Primitives

Visualizing locks, semaphores, and barriers. Essential for handling thread safety in multi-threaded environments.

Locking

Mutex

Mutual Exclusion. Only one thread can hold the resource at a time. Others must wait.

Lock lock = new ReentrantLock();
void accessResource() {
lock.lock(); // Acquire
try {
// Critical Section
} finally {
lock.unlock(); // Release
}
}
Signaling

Semaphore

Controls access to a shared resource through a counter. Allows N threads to enter.

Semaphore sem = new Semaphore(3); // 3 permits
void access() {
try {
sem.acquire(); // Decrement
// Access Resource
} finally {
sem.release(); // Increment
}
}
Busy Wait

Spinlock

Thread repeatedly checks if lock is available (busy waiting). Efficient for very short waits.

AtomicBoolean locked = new AtomicBoolean(false);
void lock() {
// Busy wait loop
while (!locked.compareAndSet(false, true));
}
void unlock() {
locked.set(false);
}
Optimization

Read-Write Lock

Multiple readers can access simultaneously, but writers require exclusive access.

ReadWriteLock rw = new ReentrantReadWriteLock();
// Multiple threads can read
rw.readLock().lock();
// Only one thread can write
rw.writeLock().lock();
Coordination

Condition Variable

zZ

Allows threads to sleep until a specific condition is met (Wait/Notify pattern).

Lock lock = new ReentrantLock();
Condition cond = lock.newCondition();
// Thread 1
lock.lock();
cond.await(); // Sleep until signaled
// Thread 2
lock.lock();
cond.signal(); // Wake up waiter