The Java Program: Kitchen2.java

  1 // Kitchen2.java -- fine granularity locking may lead to deadlock
  2 
  3 public class Kitchen2 {
  4 
  5    //  In this kitchen only one measuring cup and one mixing bowl
  6    static MeasuringCup cup = new MeasuringCup();
  7    static MixingBowl  bowl = new MixingBowl();
  8 
  9    public void makeCookies () {
 10       synchronized (cup) {
 11          cup.put (2, "flour");
 12          synchronized (bowl) {
 13             bowl.put (cup);
 14             bowl.mix ();
 15          }
 16       }
 17    }
 18 
 19    public void makeOmelette () {
 20       synchronized (bowl) {
 21          bowl.put ("eggs");
 22          bowl.mix ();
 23          synchronized (cup) {
 24             cup.put (bowl);
 25          }
 26       }
 27    }
 28 
 29    // sample main program using the kitchen
 30    public static void main (String args[]) {
 31       final Kitchen2 k = new Kitchen2 ();
 32       class SwedishChef implements Runnable {
 33          public void run () { k.makeCookies(); }
 34       }
 35       new Thread (new SwedishChef(), "Swedish Chef").start();
 36       class JuliaChild implements Runnable {
 37          public void run () { k.makeOmelette(); }
 38       }
 39       new Thread (new JuliaChild(), "Julia Child").start();
 40    }
 41 }