What is synchronization in Java?
Synchronization in Java is the mechanism by which the JVM controls access to shared resources by multiple threads, preventing data races and ensuring memory visibility.
Every Java object has an intrinsic lock (monitor). When a thread enters a `synchronized` method or block, it acquires the lock on the specified object. Other threads attempting to acquire the same lock block until the first thread releases it by exiting the synchronized scope. Synchronized methods lock on `this` (for instance methods) or on the class object (for static methods).
Synchronization provides two guarantees: 1. **Mutual exclusion**: only one thread executes the synchronized code at a time. 2. **Memory visibility**: changes made inside a synchronized block are visible to any thread that subsequently acquires the same lock (happens-before relationship in the Java Memory Model).
`volatile` is a lighter-weight alternative for visibility without mutual exclusion. A write to a volatile field is immediately visible to all threads. It does not, however, provide atomicity for compound operations — `count++` on a volatile int is still a race condition because it is a read-modify-write sequence of three operations.
The `java.util.concurrent` package provides higher-level alternatives: - `ReentrantLock`: explicit locking with `lock()` and `unlock()`, supports try-lock with timeout, fair ordering. - `ReadWriteLock`: separate locks for read and write — multiple readers can proceed concurrently; writes are exclusive. - `AtomicInteger`, `AtomicReference`, etc.: lock-free atomic operations using CPU compare-and-swap (CAS) instructions. - `CountDownLatch`, `CyclicBarrier`, `Semaphore`: coordination primitives for common concurrency patterns.
Pitfalls: holding locks for too long increases contention; synchronizing on publicly accessible objects allows external code to interfere; using `synchronized` on `String` literals or autoboxed `Integer` values shares locks unexpectedly across the codebase.
Explains the monitor/intrinsic lock model, mutual exclusion, and memory visibility, with at least one concrete alternative to synchronized.
Also covers volatile and its limitations, the JMM happens-before relationship, CAS-based atomics, and common synchronization pitfalls like over-synchronization or locking on shared objects.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment