package taskspaces.system;

import java.util.*;

/**
 * Stores messages arriving at Servers until Tasks 
 * undergoing execution by Workers can make message
 * requests.
 * @author Rob Markel, Matthew Keoshkerian 
 * @version 2.0
 */
public class MessageStore implements java.io.Serializable
{
    // Instead of checking every few seconds like it did before, it now waits until notified
    // This is logical because checking every second changes nothing whereas its notified everytime a new message is placed.

   /** Holds messages and keys. */
   private Map m=new HashMap();

   /**
    * Returns object matching given key from this store.
    * @param key the unique message identifier.
    * @return the Object stored with the matching key.
    */
   public synchronized Object get(Object key)
   {
      Object message=null;
      while((message=m.get(key))==null) 
      {     
      	try {wait();}
      	catch(InterruptedException e) {}
      }
      return message;
   }
 
   /**
    * Stores key and object for retrieval by Tasks.
    * @param key the unique message identifier.
    * @param message the message Object.
    * @return void
    */
   public synchronized void put(Object key,Object message) 
   {
       m.put(key,message);
       notifyAll();
   }

   /**
    * Clears this store of messages and associated keys.
    * @return void
    */
   public void clear() {m.clear();}
}
