Sobes.tech
Junior — Middle

Can a memory leak or deadlock occur if two threads are blocked, waiting for each other to release monitors?

sobes.tech AI

Answer from AI

Yes, such a situation is called a deadlock. If two or more threads are blocked, waiting for each other to release monitors (locks), they cannot continue because each is waiting for a resource held by the other.

This is not a memory leak, but it causes the program to hang, as threads do not release resources and do not terminate.

Example of a classic deadlock:

Object lock1 = new Object();
Object lock2 = new Object();

Thread t1 = new Thread(() -> {
    synchronized(lock1) {
        try { Thread.sleep(100); } catch (InterruptedException e) {}
        synchronized(lock2) {
            // work
        }
    }
});

Thread t2 = new Thread(() -> {
    synchronized(lock2) {
        try { Thread.sleep(100); } catch (InterruptedException e) {}
        synchronized(lock1) {
            // work
        }
    }
});

t1.start();
t2.start();

Here, t1 acquires lock1 and waits for lock2, while t2 acquires lock2 and waits for lock1 — deadlock occurs.

Can a memory leak or deadlock occur if two threads… - sobes.tech