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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.