Course contentsShow
← Java
Lesson 2652 of 2,87049. Synchronization and LockingFree lesson

The synchronized Method Modifier

Declaring synchronized instance methods and how the modifier provides automatic locking on the object instance.

The synchronized Method Modifier

What you'll learn: How to use the synchronized keyword on instance methods to automatically protect them with locks.

Core Concept

In the previous lesson, you learned why synchronization is necessary. Now you'll learn how to implement it using the simplest approach: the synchronized method modifier.

When you declare an instance method as synchronized, Java automatically acquires a lock on that object instance (this) before executing the method body. Other threads trying to call any synchronized method on the same object must wait until the lock is released.

Syntax

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

public synchronized int getCount() {
    return count;
}

The synchronized keyword goes in the method signature, just like public, private, or static.

How It Works

Think of the object instance as a building with one master key. When a thread enters a synchronized method, it takes the key. Any other thread wanting to enter any synchronized method on that same object must wait for the key to be returned.

When the method completes (normally or via exception), Java automatically releases the lock—you can't forget to unlock it.

Example with the Counter Problem

public class Counter {
    private int count = 0;
    
    public synchronized void increment() {
        count++; // Now safe from race conditions
    }
    
    public synchronized int getCount() {
        return count; // Reads are also protected
    }
}

Now multiple threads can safely call increment() without lost updates, because only one thread can execute any synchronized method at a time on each Counter instance.

Key Takeaway: The synchronized method modifier automatically locks on the object instance (this), ensuring only one thread can execute any synchronized method on that object at a time, preventing race conditions with minimal code.