What are synchronized methods and synchronized blocks

Synchronized methods and synchronized blocks are key concepts in Java that help manage concurrent access to shared resources within multithreaded environments. By ensuring that only one thread at a time can execute a synchronized method or block of code, developers can prevent data inconsistency and race conditions.

Synchronized Methods

A synchronized method is declared using the `synchronized` keyword in Java. When a method is synchronized, a thread must acquire the lock for that method's object to execute it. Other threads trying to execute any synchronized method on the same object will be blocked until the lock is released.

Synchronized Blocks

Synchronized blocks provide a more granular level of control by allowing synchronization only on specific sections of code within a method. This can improve performance since the overhead of locking is reduced compared to synchronizing an entire method.

Example


// Synchronized Method Example
class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

// Synchronized Block Example
class Counter {
    private int count = 0;

    public void increment() {
        synchronized (this) {
            count++;
        }
    }

    public int getCount() {
        synchronized (this) {
            return count;
        }
    }
}

synchronized methods synchronized blocks multithreading Java synchronization