Deadlocks are another common problem with multithreading. I’ll explain how you can get into this situation and how to change your code to avoid the problem.

This is a case where diagnosis is a lot harder than the cure. You have two options.

  1. Change how fine-grained your locks are by using fewer locks to encompass more resources.
  2. Keep the locks on individual resources and make sure to always acquire locks in the same order.

I sometimes ask a question about deadlocks during interviews and have heard some creative answers over the years. You don’t need anything complicated to handle deadlocks. Just make sure to acquire locks in the same order.

This works even if threads are asking for different numbers of locks. Let’s say that one thread wants to lock resources A, B, and C. And another thread only needs B and C. As long as both threads follow the same order for whatever locks they try to obtain, then you’ll avoid deadlocks.