Posts

Showing posts with the label AtomicLong

🛡️ Thread-Safe Programming in Java: Locks, Atomic Variables & LongAdder

Writing thread-safe code in Java requires understanding locks, atomic variables, and concurrent utilities. In this post, we'll explore ReentrantLock, synchronized blocks, AtomicLong, LongAdder , and when to use each. 1. 🔑 Synchronized Blocks The simplest way to make a section of code thread-safe is the synchronized keyword. It locks on an object monitor. public class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } ✅ Easy to use for simple critical sections ❌ Locks the entire object, can reduce concurrency 2. 🔄 ReentrantLock More flexible than synchronized blocks. Supports tryLock , timed locks, and interruptible locks. import java.util.concurrent.locks.ReentrantLock; ReentrantLock lock = new ReentrantLock(); lock.lock(); try { // critical section } finally { lock.unlock(); } ✅ Better for advanced locking strategies, fairnes...