The synchronized keyword in Java restricts a section of code so that only one thread at a time can execute it, by requiring the thread to first acquire the intrinsic monitor lock associated with a given object or class.
Key Points: • On an instance method, synchronized locks on "this"; on a static method, it locks on the Class object; on a block, it locks on whatever object you specify. • When a thread enters a synchronized section, it acquires the associated lock; any other thread trying to enter a section guarded by the same lock must wait until it's released. • The lock is automatically released when the thread exits the synchronized section, whether normally or via an exception. • Because it's reentrant, a thread already holding a lock can enter another synchronized section guarded by the same lock without blocking itself. • synchronized guarantees both mutual exclusion and visibility — changes made inside a synchronized block are guaranteed visible to the next thread that acquires the same lock.
Example: Two threads calling a synchronized increment() method on the same Counter object will never execute the method body at the same time — the second thread simply waits until the first one finishes and releases the lock.
Code Example:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}Interview Tip: A concise interview answer is:
"synchronized ensures only one thread can execute a given critical section at a time by requiring it to acquire a monitor lock first — on the instance, the class, or an explicit object depending on how it's used. It's reentrant, releases automatically even on exceptions, and guarantees the resulting changes are visible to the next thread that acquires the same lock."