Avoiding Deadlocks with wait() and notify()

So now we've seen how threads can prevent corrupting shared data. There's now a new problem that, unfortunately, we've introduced. That problem is the potential for deadlock, or the "deadly embrace." Here's how it works.

Consider two threads, t1 and t2. Both threads need to work with two resources, obj1 and obj2, in order to complete their work. Now, here's the problem scenario.

  1. t1 gets an object lock for obj1.

  2. t2 gets an object lock for obj2.

  3. t1 can't proceed without the object lock for obj2, but t1 can't get that lock because t2 owns it.

  4. t2 cannot proceed without obj1, but it cannot get that object lock because t1 owns it.

The result of this scenario is a deadlock. Because neither thread ...

Get PURE Java™ 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.