Concurrent Programming with Java
Lab Manual, Version 1.0, F. Astha Ekadiyanto, 2002.

[Contents] [Next] [Previous]

Lab 6: Monitors and Thread Synchronization 2


Dining Philosophers scenario: Fork Class

The Fork () is the shared object of the Dining Philosophers scenario.The Fork will have two important methods namely get() and put(). When the get() method called, the process will check whether the fork is taken or not. If it is taken, then the process will be asked to wait until some other process notify (signal condition) and retry to get it again.

This Class will surely exhibit the first criteria of processes that may lead to deadlock, which is Serially reusable resources.

The Fork Class definition is very straight forward as shown below.

Class name : Fork

public class Fork
/**
 * The class Fork implements a shared object.
 * Modified from Stephan Fischli's Phillosophers Code
 */

{
   /**
   * The user of the fork.
   */
   private Thread user = null;
   /**
   * Returns true if the fork is used, false otherwise.
   */
   public boolean taken()
   {
       return user != null;
   }
   /**
   * Get the fork. If available, the calling thread becomes the user.
   * Otherwise the calling thread must wait until the fork is available.
   */
   public synchronized void get()
   {
       Thread caller = Thread.currentThread();
       while ( taken() ) 
       try { wait(); }
       catch ( InterruptedException e ) {}
       user = caller;
   }
   /**
   * Putdown the fork. The calling thread must be the current user of the fork.
   */
   public synchronized void put()
   {
       Thread caller = Thread.currentThread();
       if ( caller == user ) {
           user = null;
           notifyAll();
       }
   }
}
 

[Contents] [Next] [Previous]