What will happen if two threads try to acquire two locks in opposite order?

Last Updated :
Discuss
Comments

What will happen if two threads try to acquire two locks in opposite order?

Java
class A {
    synchronized void method1(B b) {
        b.last();
    }
    synchronized void last() {}
}

class B {
    synchronized void method1(A a) {
        a.last();
    }
    synchronized void last() {}
}

One thread will succeed

The program will throw an exception

Deadlock will occur

Both threads will run concurrently

Share your thoughts in the comments