Consider the following code snippet. Which of the following will result in a deadlock?

Last Updated :
Discuss
Comments

Consider the following code snippet. Which of the following will result in a deadlock?

Java
class A {
    Lock lock1 = new ReentrantLock();
    Lock lock2 = new ReentrantLock();

    void method1() {
        lock1.lock();
        lock2.lock();
        try {
            
          // Critical section
        } finally {
            lock1.unlock();
            lock2.unlock();
        }
    }
}

class B {
    Lock lock1 = new ReentrantLock();
    Lock lock2 = new ReentrantLock();

    void method1() {
        lock2.lock();
        lock1.lock();
        try {
            // Critical section
        } finally {
            lock1.unlock();
            lock2.unlock();
        }
    }
}

No deadlock will occur

Deadlock will occur if A.method1() and B.method1() are executed simultaneously

ReentrantLock always prevents deadlock

The code will fail due to incorrect usage of ReentrantLock

Share your thoughts in the comments