Object Oriented Design and the Dining Philosophers


[buzzword mode on]
This version is designed to be object oriented, more reusable, and conformant to rigid GUI/algorithm separation using the Model-View design pattern.
[buzzword mode off]

What that means is I made several different classes that implement different aspects of the Dining Philosophers problem. There are classes that do the GUI, and classes that do the algorithm alone and could be reused with a different GUI or multiple GUIs. Java's Observable and Observer classes allowed me to make the distinct separation between GUI and algorithm (the Model-View design pattern).

Design

In brief, each Philosopher is a Runnable (Thread) as well as an Observable object. The GUI is an Observer object. When a Philosopher changes state, it notifies all Observers and the observing GUI updates itself. The Philosophers themselves compete for the Stick objects that occupy place settings on the table. It is these StickSettings that are the shared point of access for the Philosophers, so it is there that the synchronized methods for accessing the Sticks are.

Ensuring single thread access to the sticks

If two philosophers reach for the same stick at the same time, some sort of mechanism is required to ensure that only one philosopher gets the stick. This is done using Java's synchronized methods. When a philosopher's thread enters the synchronized method to get a stick, no other philosopher's thread may enter until the stick is picked up. When the second philosopher enters the synchronized method, he blocks until a stick is placed on the table again.

Avoiding deadlock and starvation

These problems are avoided by a simple algorithm. One stick is marked and if a philosopher picks up the marked stick, he must put it down and reach for the other stick first. When a philosopher is done eating, he swaps his sticks and puts them down. This ensures the marked stick will not stay in the same place.

The Graphics

The excellent representation of the Philosophers eating, thinking, and getting hungry was done using povray2.3 (presumably by one of the authors of Hooked On Java, though there was no copyright directly associated with them.)

I changed the graphics a little bit, by adding eye movement that indicates which stick a Philosopher is waiting for.

  • When the Philosopher is thinking, the eyes move randomly around.
  • When the Philosopher is waiting for a stick that someone else has, he looks angry and he stares at the person he's waiting for.
  • When the Philosopher is eating he chomps away and makes a chomping noises (unless the Laughing, Talking, or Mute Philosophers option is selected instead).

    The source code: [4 space tabs, formatting may be off on your browser]

  • Philosopher.java
  • DiningPhilosophers.java
  • DiningPhilosophersApplet.java
  • DiningPhilosophersComponent.java
  • Slider.java
    Last update: Septmeber 15, 1997.
    David Whitney