Synchronization in Java
Synchronization in Java is the mechanism that controls access to shared resources by multiple threads. Without it, concurrent modifications to the same dat...
The synchronized Keyword
Synchronization in Java is the mechanism that controls access to shared resources by multiple threads. Without it, concurrent modifications to the same data produce unpredictable results. The synchronized keyword is the most fundamental synchronization tool in Java, operating through object monitors also called intrinsic locks.
Every Java object has a monitor. When a thread enters a synchronized method or block, it acquires that object's monitor. Any other thread that tries to enter a synchronized section guarded by the same monitor is blocked until the first thread exits and releases it. This guarantees that only one thread executes the critical section at a time.
Synchronized methods lock on the instance (this) for instance methods and on the Class object for static methods:
public synchronized void deposit(int amount) { balance += amount; }
public static synchronized void logTransaction(String msg) { System.out.println(msg); }
You can also use synchronized blocks with an explicit lock object, which gives you finer-grained control. Locking on a dedicated object rather than this prevents other synchronized methods from blocking unnecessarily:
private final Object lock = new Object(); public void withdraw(int amount) { synchronized (lock) { if (balance >= amount) balance -= amount; } }
The synchronized keyword provides two guarantees: mutual exclusion (only one thread executes the guarded code at a time) and memory visibility (changes made inside a synchronized block are visible to all threads that subsequently enter a synchronized block on the same monitor).
Synchronization does not come free. It reduces parallelism because threads must wait for the lock. Holding a lock for a long time increases contention. Minimize the size of synchronized sections to only the code that truly requires exclusive access, and avoid calling external methods or doing I/O while holding a lock.
Interview tip: Explain that synchronization prevents race conditions but does not eliminate deadlocks. Two threads can each hold a lock the other needs, creating a circular wait. Always acquire multiple locks in a globally consistent order to prevent this.
Volatile and Atomic Variables
The volatile keyword and the classes in java.util.concurrent.atomic address two different aspects of thread safety: visibility and atomicity. Understanding the difference is crucial because each solves a distinct class of concurrency problems.
When a variable is marked volatile, the JVM guarantees that every read of that variable sees the most recent write from any thread. Without volatile, the JVM may cache variable values in CPU registers or per-core caches, causing threads to work with stale copies. Volatile ensures all threads see a consistent value by always reading from and writing to main memory.
private volatile boolean shutdownRequested = false;
However, volatile does not make compound operations atomic. An operation like counter++ consists of three steps: read the current value, increment it, and write it back. If two threads both read the same value before either writes back, one increment is lost. Volatile alone cannot prevent this.
The atomic classes in java.util.concurrent.atomic solve this problem. AtomicInteger, AtomicLong, AtomicBoolean, and AtomicReference provide operations that are both visible and atomic, using hardware-level compare-and-swap (CAS) instructions rather than locking:
AtomicInteger counter = new AtomicInteger(0); counter.incrementAndGet(); // atomic read-modify-write counter.compareAndSet(5, 10); // update only if current value is 5
AtomicInteger.incrementAndGet() is equivalent to a synchronized increment but faster because it avoids lock acquisition overhead. CAS operations retry automatically if another thread modifies the value between the read and write, making them lock-free but not wait-free.
For cases where you need multiple related fields to be updated atomically, atomic variables are insufficient. Use synchronized blocks instead to ensure the entire compound update is treated as a single indivisible operation.
Interview tip: When asked about the limitations of volatile, explain the classic double-checked locking pattern. Marking a reference volatile is necessary for the pattern to work correctly in Java because without it, the JVM may publish a partially constructed object to other threads.
Locks and ReentrantLock
While the synchronized keyword is convenient, it has limitations. You cannot try to acquire a lock without blocking indefinitely, you cannot interrupt a thread waiting for a lock, and you cannot implement fair lock ordering. The java.util.concurrent.locks.Lock interface and its primary implementation ReentrantLock address all of these shortcomings.
ReentrantLock offers the same mutual exclusion and memory visibility guarantees as synchronized, but with additional capabilities. The name "reentrant" means that a thread that already holds the lock can acquire it again without blocking itself. The synchronized keyword is also reentrant, so both approaches handle recursive locking correctly.
import java.util.concurrent.locks.ReentrantLock; ReentrantLock lock = new ReentrantLock(); lock.lock(); try { // critical section } finally { lock.unlock(); }
Always place unlock() in a finally block. If the critical section throws an exception, the lock must still be released; otherwise all other threads waiting for it will block forever. This is a difference from synchronized, which automatically releases the lock when the block exits for any reason.
The tryLock() method is a key advantage of ReentrantLock. It attempts to acquire the lock and returns immediately with a boolean result, so the calling thread is never forced to wait. You can also call tryLock(time, unit) with a timeout, which is useful for avoiding deadlocks in situations where waiting indefinitely would be unacceptable.
ReentrantLock supports a fairness policy. When constructed with new ReentrantLock(true), threads acquire the lock in the order they requested it, preventing starvation of threads that have been waiting the longest. Fair locks have lower throughput than unfair ones but provide predictable access ordering.
ReadWriteLock, also available in the package, allows multiple threads to read simultaneously while exclusive access is required for writes, making it ideal for read-heavy data structures.
Interview tip: Describe a scenario where tryLock() with a timeout is preferable to synchronized. A good answer covers situations where you must avoid deadlock in a system with multiple locks, where you want to fall back to an alternative action if the resource is busy, or where you must enforce a maximum latency guarantee.