JavaIntermediate#concurrency

What is the difference between synchronized methods and synchronized blocks?

A synchronized method locks the entire method using 'this' (or the class object for static methods) as the monitor. A synchronized block locks only the specified critical section on a chosen object, allowing finer-grained control and better performance.

Example
public void increment() { synchronized(this) { count++; } } // fine-grained
// vs
public synchronized void increment() { count++; } // whole method locked

Related Questions

1
JavaIntermediate#concurrency

What are atomic classes like AtomicInteger used for?

Open
2
JavaAdvanced#concurrency

What is a CountDownLatch?

Open
3
JavaAdvanced#concurrency

What is a ThreadLocal and when would you use it?

Open