Interview Q&A · Java · 11 questions in this topic

Synchronization, Locks and Monitors — Java Interview Q&A

All Java topics

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

  1. 1Synchronized instance or static methods that lock the whole method.
  2. 2Synchronized blocks that lock a chosen object for a smaller region.
  3. 3Explicit Lock objects such as ReentrantLock with try and finally unlocking.
  4. 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

Example.javajava
public synchronized void increment() {
    count = count + 1;
}
public static synchronized void reset() {
    count = 0;
}

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits