How to do it...

Follow these steps to implement the example:

  1. Create a class named BadLocks with two methods, named operation1() and operation2():
        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();             }           }            public void operation2(){             lock2.lock();             lock1.lock();              try {               TimeUnit.SECONDS.sleep(2);             } catch (InterruptedException e) {               e.printStackTrace();             } finally {               lock1.unlock();               lock2.unlock();             }           }          }
  1. Let's analyze the preceding code. If a thread ...

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.