What is the difference between a synchronized method and a synchronized block in Java?
A synchronized method locks the whole method on this (or the Class for static methods). A synchronized block locks only the lines inside it, on any object you pick, so threads wait less and you can use separate locks for separate data.
Explain it simply
A synchronized method is like locking the whole shop whenever one customer is being billed. A synchronized block locks only the billing counter, so others can still browse the shelves.
Example
class Counter {
private int count = 0;
private final Object lock = new Object();
synchronized void incrementAll() { // locks on 'this' for the entire method
count++;
}
void incrementPart() {
System.out.println("not locked"); // many threads can run this together
synchronized (lock) { // only this part is locked
count++;
}
}
static synchronized void classLevel() { } // locks on Counter.class
}What to say in the interview
"Both give mutual exclusion and visibility of changes between threads. A synchronized instance method takes the lock of the current object, and a static one takes the lock of the Class object. A block lets me narrow the critical section and choose the lock, so unrelated operations do not block each other. I prefer a private final lock object, because outside code cannot also synchronize on it and cause surprises."
Common mistakes
- Locking on a String literal or a boxed Integer, which may be shared across unrelated code.
- Synchronizing on different objects and expecting mutual exclusion.