WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Core Java · Advanced · question 52 of 100

What is the difference between ReentrantLock and synchronized keyword in Java?

📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

In Java, both ReentrantLock and synchronized keyword are used to provide mutual exclusion and synchronize access to shared resources among threads. However, there are some differences between them:

Locking mechanism: synchronized keyword is implemented as an implicit lock acquired by the executing thread while entering a synchronized block or method. On the other hand, ReentrantLock is implemented as an explicit lock object that is acquired and released by the thread explicitly.

Fairness: By default, synchronized keyword provides no fairness guarantee. In other words, there is no guarantee that the waiting threads will acquire the lock in the order they requested it. However, ReentrantLock can be configured to provide a fair locking policy where the longest-waiting thread gets the lock first.

Try locking: ReentrantLock provides a non-blocking tryLock() method that tries to acquire the lock and returns immediately without blocking the calling thread if the lock is not available. On the other hand, synchronized keyword does not provide any equivalent non-blocking mechanism.

Interruptible locking: ReentrantLock provides an lockInterruptibly() method that allows the thread to be interrupted while waiting to acquire the lock. On the other hand, synchronized keyword does not provide any equivalent interruptible mechanism.

Here’s an example code that illustrates the usage of ReentrantLock and synchronized keyword:

import java.util.concurrent.locks.ReentrantLock;

public class LockExample {
    private int count;
    private final ReentrantLock lock = new ReentrantLock();
    
    public synchronized void increment() {
        count++;
    }
    
    public void incrementWithLock() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
    
    public int getCount() {
        return count;
    }
}

In this example, increment() method is synchronized using the synchronized keyword. On the other hand, incrementWithLock() method uses ReentrantLock for synchronization. Both methods increment the shared count variable in a thread-safe way. The getCount() method returns the current value of count.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Core Java interview — then scores it.
📞 Practice Core Java — free 15 min
📕 Buy this interview preparation book: 100 Core Java questions & answers — PDF + EPUB for $5

All 100 Core Java questions · All topics