Mastering Java’s synchronized: When and How to Lock Objects, Methods, and Classes

This article explains why thread safety is essential in concurrent Java programs, introduces the lock concept, and provides detailed examples of using the synchronized keyword to protect code blocks, instance methods, static methods, and entire classes, including common pitfalls and inheritance rules.

AI Code to Success
AI Code to Success
AI Code to Success
Mastering Java’s synchronized: When and How to Lock Objects, Methods, and Classes

Thread safety and lock concept

In concurrent Java programs, multiple threads may share critical resources. Without coordination, race conditions occur. A lock guarantees exclusive execution of a critical section. The synchronized keyword implements a monitor‑based lock.

Using synchronized

1. Synchronizing a code block

Lock a specific block by synchronizing on an object reference, e.g. synchronized(this). Only one thread that enters the block on the same monitor can execute; other threads block until the lock is released.

/**
 * Demonstrates a synchronized block
 */
public class SynThread implements Runnable {
    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 5; i++) {
                try {
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Running two Thread instances that share the same SynThread object produces sequential output (e.g. SynThread1:0 … SynThread1:4 followed by SynThread2:0 … SynThread2:4), confirming that the object lock serializes access.

2. Synchronizing a method

Two equivalent declarations exist:

// Form 1 – method declaration
public synchronized void method() {
    // critical section
}

// Form 2 – synchronized block inside method
public void method() {
    synchronized (this) {
        // critical section
    }
}

Key rules:

The synchronized modifier is not inherited. Subclasses must redeclare it to obtain synchronization.

Interface methods cannot be declared synchronized.

Constructors cannot be declared synchronized, but they may contain synchronized(this) blocks.

3. Synchronizing a static method

A static method acquires a lock on the Class object, so all instances of the class share the same lock.

public static synchronized void staticMethod() {
    // critical section
}

When two different instances invoke a static synchronized method, they contend for the same class‑level lock, producing the same sequential behavior as instance‑level synchronization.

4. Synchronizing on a class object

Explicitly locking on ClassName.class protects a block across all instances of the class.

class ClassName {
    public void method() {
        synchronized (ClassName.class) {
            // critical section
        }
    }
}

This ensures that any thread, regardless of which instance it uses, must acquire the same lock before entering the block.

Important considerations

Lock scope : instance‑level locks ( synchronized(this) or synchronized instance methods) protect a single object; class‑level locks ( static synchronized or ClassName.class) protect the entire class.

Inheritance : the synchronized keyword is not inherited. Overriding a synchronized method in a subclass requires an explicit synchronized modifier if synchronization is desired.

Interfaces : methods declared in an interface cannot be marked synchronized.

Constructors : constructors cannot be declared synchronized, but they may contain synchronized blocks to protect shared initialization code.

lockingThread Safetymultithreadingsynchronized
AI Code to Success
Written by

AI Code to Success

Focused on hardcore practical AI technologies (OpenClaw, ClaudeCode, LLMs, etc.) and HarmonyOS development. No hype—just real-world tips, pitfall chronicles, and productivity tools. Follow to transform workflows with code.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.