Rui
Rui

Reputation: 3667

Does the following code cause deadlock when running

When running the following code, the main thread is locked on the instance of MainDealock infinitely

    public class MainDeadlock {
      public synchronized void lock() throws InterruptedException {
        wait();
      }

      public static void main(String[] args) throws InterruptedException {
        new MainDeadlock().lock();
      }
    }

However, I can not figure out any circular wait as there is only one thread, i.e. the main thread

Question: May I still say there is a deadlock in this case?

Upvotes: 0

Views: 62

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96424

No, you need at least 2 threads for a deadlock, where they keep each other from progressing because they’re each holding onto something the other needs.

This code doesn’t hold onto a lock. For a thread to call wait it must have the lock, but once it begins waiting it releases the lock.

All you have here is a thread waiting on a notify that never comes. When you call wait with no timeout specified then the thread will go dormant until:

  • some other thread calls notify on the lock that the waiting thread used to call wait, or

  • until another thread calls interrupt on the waiting thread or

  • until you get tired of it and kill the process.

Upvotes: 1

Related Questions