HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"Designing Objects for Concurrency in Java", part 2
Vol. 2, Issue 6, p. 14

	

Listing 1

/** Interface for a Generic Container */
interface Container {
   public final static int SIZE = 100;
   public abstract void store(Object o);
   public abstract Object retrieve();
}

/** Base class defines: put and get methods */
public abstract class BoundedContainer 
                                implements Container {

   protected int currentSize = 0;
   /** put adds an object to container */
   public synchronized void put(Object o) {
      while (currentSize == SIZE) {
         try {
           wait();
         }
         catch (Exception e) { }
      }
      store(o);
      currentSize++;
      if (currentSize == 1)
         notify(); 
   }
   /** get removes an object from container */
   public synchronized Object get() {
      while (currentSize == 0) {
         try {
           wait();
         }
         catch (Exception e) { }
      }
      Object o = retrieve();
      currentSize--;
      if (currentSize == SIZE - 1)
         notify(); 
      return o;
   }
   /** isEmpty defines the state */
   public synchronized boolean isEmpty() {
      return (currentSize == 0); 
   }
}

Listing 2

/** Extended class adds a new method: gget */
public abstract class ExtBoundedContainer 
                        extends BoundedContainer {

   protected boolean lastGet = false;
   /** put records the use of get method
       and uses the superclass method */
   public synchronized void put(Object o) {
      super.put(o);
      lastGet = false;
   }
   /** get records its invocation 
       and uses the superclass method */
   public synchronized Object get() {
      Object o = super.get();
      lastGet = true;
      return o;
   }
   /** gget implements the fuctionality required 
         in Matsuoka's problem [2] */
   public synchronized Object gget() {
      while (currentSize == 0 || lastGet == false) {
         try {
           wait();
         }
         catch (Exception e) { }
      }
      return get();
   }
}


 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.