I wrote this code to overcome the deadlock condition described in this Oracle tutorial.Summary of Problem:Alphonse and Gary are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.I used a volatile boolean CanBow() to check if either of the friends are bowing so that the condition when both of them bow and wait for the other to bow back will not happen.Is this a valid way to handle deadlocks as opposed to using locks?public class NewThread extends Thread {    Friend bower;    Friend bowBack;    NewThread(Friend bower,Friend bowBack){       this.bower = bower;       this.bowBack = bowBack;    }    @Override    public void run(){       if(bowBack.canBow())             bower.bow(bowBack);    }}public class ApplicationThread {    public static void main(String[] args) {           final Friend alphonse = new Friend(Alphonse);        final Friend gary = new Friend(Gary);        NewThread t1 = new NewThread(alphonse,gary);        NewThread t2 = new NewThread(gary,alphonse);        t1.start();        t2.start();    }    static class Friend {        private final String name;        private volatile boolean canBow;        public Friend(String name) {            this.name = name;            canBow = true;        }        public String getName() {            return this.name;        }        public boolean canBow(){            return canBow;        }        public synchronized void bow(Friend bower) {                canBow = false;                System.out.format(%s: %s                    +   has bowed to me!%n,                     this.name, bower.getName());                bower.bowBack(this);                canBow = true;        }        public synchronized void bowBack(Friend bower) {            System.out.format(%s: %s                +  has bowed back to me!%n,                this.name, bower.getName());        }    }}
Volatile boolean to prevent deadlock
java;multithreading