0Pricing
Java Academy · Lesson

ReentrantLock vs synchronized

Compare ReentrantLock features (tryLock, lockInterruptibly, fairness) with the synchronized keyword.

The synchronized Keyword

Java's synchronized keyword provides mutual exclusion using the object's intrinsic lock (monitor). Simple but limited — no timeout, no fairness, no interruptibility.

class Counter {
    private int count = 0;
    
    synchronized void increment() {
        count++; // only one thread at a time
    }
    
    synchronized int get() { return count; }
}

Counter c = new Counter();
// Multiple threads can safely call increment()

ReentrantLock Basics

ReentrantLock is an explicit lock from java.util.concurrent.locks. It provides the same mutual exclusion as synchronized but with more control. The lock must be manually released in a finally block.

import java.util.concurrent.locks.*;

class SafeCounter {
    private int count = 0;
    private final ReentrantLock lock = new ReentrantLock();
    
    void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock(); // always release in finally!
        }
    }
    
    int get() {
        lock.lock();
        try { return count; }
        finally { lock.unlock(); }
    }
}

All lessons in this course

  1. ReentrantLock vs synchronized
  2. ReadWriteLock for Reader-Writer Scenarios
  3. Atomic Variables: Lock-Free Updates
  4. StampedLock and Optimistic Reads
← Back to Java Academy