How it works...

Using this rule, you will avoid deadlock situations. For example, in the case presented earlier, you can change operation2() to first get lock1 and then lock2. Now if both operation1() and operation2() execute their respective first sentences, one of them will be blocked waiting for lock1 and the other will get lock1 and lock2 and they will do their operations. After this, the blocked thread will get the lock1 and lock2 locks and it will do its operation.

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.