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

Synchronized on this vs Dedicated Lock Objects

Compare synchronizing on this versus using private final Object lock fields for better encapsulation.

Synchronized on this vs Dedicated Lock Objects

What you'll learn: You'll understand why using a dedicated private lock object is often safer than synchronizing on this.

When you write synchronized(this) or use a synchronized method, you're using the object itself as the lock. While this works, it exposes your lock to the outside world—any external code that has a reference to your object can also synchronize on it, potentially causing unexpected blocking or deadlocks.

The Problem with synchronized(this)

public class Counter {
    private int count = 0;

    public void increment() {
        synchronized(this) {  // Uses Counter instance as lock
            count++;
        }
    }
}

// External code can interfere:
Counter c = new Counter();
synchronized(c) {  // Acquires the same lock!
    // Blocks other threads from increment()
    Thread.sleep(10000);
}

External code can "hijack" your lock, breaking your internal synchronization strategy.

The Solution: Dedicated Lock Objects

public class Counter {
    private final Object lock = new Object();  // Private, encapsulated lock
    private int count = 0;

    public void increment() {
        synchronized(lock) {  // Uses private lock
            count++;
        }
    }
}

// External code CANNOT interfere:
Counter c = new Counter();
synchronized(c) {  // Different lock—no impact on increment()
    Thread.sleep(10000);
}

By using a private final Object as your lock, you encapsulate the synchronization mechanism. External code cannot access or interfere with your lock, giving you complete control over your threading behavior.

When to Use Each

  • synchronized(this): Simple cases where you control all code that accesses the object
  • Dedicated lock: Production code, public APIs, libraries, or whenever external synchronization might occur

Key Takeaway: Use dedicated private final Object lock fields instead of synchronizing on this to prevent external code from interfering with your internal synchronization and to maintain better encapsulation.