O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required