Avoiding deadlocks by ordering locks
When you need to acquire more than one lock in the methods of your application, you must be very careful with the order in which you get control of your locks. A bad choice can lead to a deadlock situation.
In this recipe, you will implement an example of a deadlock situation, then learn how to solve it.
How to do it...
Follow these steps to implement the example:
- Create a class named
BadLocks
with two methods, namedoperation1()
andoperation2()
:
public class BadLocks { private Lock lock1, lock2; public BadLocks(Lock lock1, Lock lock2) { this.lock1=lock1; this.lock2=lock2; } public void operation1(){ lock1.lock(); lock2.lock(); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock2.unlock(); lock1.unlock...