Sobes.tech
Junior — Middle

What are the differences between using the synchronized keyword for a method and for a block of code inside a method?

sobes.tech AI

Answer from AI

The synchronized keyword in Java is used to ensure mutual exclusion when accessing a critical section of code.

Differences between synchronized for a method and for a block inside a method:

  • Synchronized method:

    • Synchronizes the entire method.
    • If the method is non-static, the lock is on the object (this).
    • If the method is static, the lock is on the class object (Class).
  • Synchronized block inside a method:

    • Allows synchronizing only a part of the method.
    • You can explicitly specify the object on which the lock occurs, e.g., synchronized(this), synchronized(lockObject).
    • More flexible approach, reduces the duration of lock holding.

Example:

public class Example {
    private final Object lock = new Object();

    public synchronized void syncMethod() {
        // entire method is synchronized on this
    }

    public void syncBlock() {
        // part of the method is synchronized
        synchronized(lock) {
            // critical section
        }
    }
}

Using a synchronized block inside a method allows more precise control over the synchronization scope and can improve performance by reducing lock duration.