Posts

Showing posts with the label Thread Safety

πŸ›‘️ 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...

πŸ—Ί️ Java Maps Explained: HashMap vs Hashtable vs ConcurrentHashMap

Java provides several map implementations, but not all of them are suitable for multi-threaded environments. Choosing the wrong one can lead to performance bottlenecks, thread-safety issues, or even corrupted data. In this post, we’ll explore HashMap, Hashtable, and ConcurrentHashMap , explain when to use each, and dive into how ConcurrentHashMap works under the hood. 1. 🏎️ HashMap HashMap is the standard, non-thread-safe map in Java. Allows null keys/values and provides fast lookups (O(1) average). Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); Integer value = map.get("apple"); ✅ Fast and memory-efficient for single-threaded applications ❌ Not thread-safe, requires external synchronization in multi-threaded code 2. 🧱 Hashtable Hashtable is a legacy, thread-safe map. All methods are synchronized, so only one thread can access any method at a time. Map<String, Integer> map...