Avoiding deadlocks

You have to be very careful with the use of locks to avoid deadlocks. This situation occurs when two or more threads are blocked while waiting for locks that will never be unlocked. For example, thread (A) locks Lock (X) and thread (B) locks Lock (Y). Now, if thread (A) tries to lock Lock (Y) and thread (B) simultaneously tries to lock Lock (X), both the threads will be blocked indefinitely because they are waiting for locks that will never be liberated. Note that the problem occurs because both threads try to get the locks in the opposite order. The Appendix, Concurrent Programming Design, provides some good tips to design concurrent applications adequately and avoid these deadlock problems.

Get Java 9 Concurrency Cookbook - Second Edition 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.