Interview Q&A · Java · 11 questions in this topic
Synchronization, Locks and Monitors — Java Interview Q&A
How synchronized methods, blocks, and class-level locks protect shared state in Java. Part of Threads & Concurrency · 294 questions in the Java bank.
What is a lock (monitor)?
Answer
A lock, also called a monitor, is a mutual exclusion mechanism that protects shared state. Only one thread at a time may hold the monitor for a given object, so critical sections guarded by the same lock run one after another. In Java every object has an associated monitor that synchronized methods and blocks use. Higher level code can also use explicit Lock objects from java.util.concurrent.locks for the same purpose with more features.
How many ways can code be synchronized?
Answer
The language provides synchronized methods and synchronized blocks, both of which use object monitors. Synchronized methods lock the whole method on this or on the Class object for static methods, while synchronized blocks lock only the chosen region on a chosen object. Modern Java adds Lock implementations such as ReentrantLock, plus concurrent collections and atomic variables that often remove the need for explicit synchronization. Interviews usually expect the two classic forms plus a mention of the concurrent package.
Key points
- 1Synchronized instance or static methods that lock the whole method.
- 2Synchronized blocks that lock a chosen object for a smaller region.
- 3Explicit Lock objects such as ReentrantLock with try and finally unlocking.
- 4Lock-free alternatives such as concurrent collections and atomic variables.
What are synchronized methods?
Answer
A synchronized method acquires the monitor of its object when a thread enters and releases it when the thread exits. For an instance method the lock is the this object, and for a static method the lock is the Class object. Only one thread at a time can execute any synchronized method on the same lock. This makes synchronized methods a simple way to guard mutable shared state, at the cost of locking the whole method.
Example
public synchronized void increment() { count = count + 1; } public static synchronized void reset() { count = 0; }
When are synchronized methods used?
Answer
They are used when mutable state is shared between multiple threads and operations on it must appear atomic. Typical examples are counters, caches, and read-modify-write sequences that would race if interleaved. Synchronization ensures only one thread executes the protected logic at a time and makes changes visible to other threads. For simple counters, atomic classes are now often cleaner, but synchronized methods remain the textbook answer.
Can two threads run synchronized methods of the same object simultaneously?
Answer
No, two threads cannot execute synchronized instance methods of the same object at the same time. Both methods compete for the same monitor, so one thread holds it while the other waits outside. The exception is mixing static and instance synchronization, because static methods lock the Class object while instance methods lock the instance. Two threads can therefore run a static synchronized method and an instance synchronized method of the same class concurrently.
Can a thread in a synchronized method call another synchronized method of the same object?
Answer
Yes, this is allowed because Java monitors are reentrant. A thread that already holds a monitor may enter any other block guarded by the same monitor without deadlocking itself. The JVM keeps a hold count and releases the lock only when the outermost synchronized region exits. Without reentrancy, even simple patterns such as one synchronized method calling another would deadlock.
What are synchronized blocks?
Answer
A synchronized block is a region marked with synchronized followed by a lock object in parentheses. Only one thread at a time can execute code inside blocks that share the same lock object. Unlike a synchronized method, the block can cover just a few statements and can choose any object as the lock. This finer control usually gives better performance than locking a whole method.
Example
private final Object lock = new Object(); public void add(int x) { synchronized(lock) { items.add(x); } }
When are synchronized blocks preferred?
Answer
They are preferred when only part of a method touches shared state. Locking a smaller critical section reduces contention, so other threads wait for less time. Blocks also let you pick a private lock object instead of exposing this as the lock. The result is the same safety with better throughput and encapsulation.
What is a class-level lock?
Answer
A class-level lock is the monitor associated with a Class object, for example Counter.class. Code guarded by this lock is mutually exclusive across all instances of the class, not just one object. It is the natural way to protect static mutable state shared by every instance. Static synchronized methods and synchronized blocks on the Class object both use this lock.
Example
public void resetAll() { synchronized(Counter.class) { Counter.total = 0; } }
Can static methods be synchronized?
Answer
Yes, a static method may be declared synchronized. It acquires the monitor of the Class object rather than any instance. That means it does not block instance synchronized methods, which lock individual objects, but it does block other static synchronized methods of the same class. Use it to guard static fields that multiple threads may update.
Example
public static synchronized int nextId() { return ++counter; }
Can a synchronized block lock a primitive?
Answer
No, a synchronized block requires an object reference in parentheses. Primitives such as int or boolean have no monitor, so attempting to lock one is a compile error. You must lock a suitable object, ideally a private final lock object. Locking publicly visible objects or boxed primitives is discouraged because other code might lock the same object unexpectedly.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission