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

Java Concurrency · Basic · question 17 of 100

How would you define a reentrant lock in Java?

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

In Java, a ReentrantLock is a type of lock that allows a thread to acquire the same lock multiple times without blocking. This makes it possible for a thread to enter a synchronized block or method that it already holds a lock on, preventing deadlocks and improving the efficiency of the application.

Here’s an example of how to define a ReentrantLock in Java:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    private Lock lock = new ReentrantLock();

    public void doSomething() {
        lock.lock();
        try {
            // Critical section of code
        } finally {
            lock.unlock();
        }
    }
}

In this example, we define a ReentrantLock object and use it to protect a critical section of code in the doSomething() method. The lock() method is called to acquire the lock on the mutex, and the try-finally block is used to ensure that the lock is always released, even if an exception is thrown in the critical section of code.

Overall, a ReentrantLock is a powerful tool for managing access to shared resources in a multi-threaded application. By allowing threads to acquire the same lock multiple times, a ReentrantLock prevents deadlocks and improves the efficiency of the application.

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

All 100 Java Concurrency questions · All topics