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       // Use oven
 18    }
 19 
 20    public void makeOmelette () {
 21       synchronized (bowl) {
 22          bowl.put ("eggs");
 23          bowl.mix ();
 24          synchronized (cup) {
 25             cup.put (bowl);
 26          }
 27       }
 28       // Use range
 29    }
 30 
 31    // sample main program using the kitchen
 32    public static void main (String args[]) {
 33       final Kitchen2 k = new Kitchen2 ();
 34       class SwedishChef implements Runnable {
 35          public void run () { k.makeCookies(); }
 36       }
 37       new Thread (new SwedishChef(), "Swedish Chef").start();
 38       class JuliaChild implements Runnable {
 39          public void run () { k.makeOmelette(); }
 40       }
 41       new Thread (new JuliaChild(), "Julia Child").start();
 42    }
 43 }