
// PongAgent.java
// Michele Loreti and the jSpace Developers, 2017
// Modified by Andrew Davison, ad@coe.psu.ac.th, May 2023

/* One side of a two-way communication between the PingAgent
   and PongAgent threads using two spaces called PingSpace
   and PongSpace.

   PingAgent reads 'ping' tuples from the PingSpace, which
   are placed there by PongAgent.

   PongAgent reads 'pong' tuples from the PongSpace, which
   are placed there by PingAgent.

   An agent only writes a tuple after it has read one of its
   tuples. Deadlock is avoided by having PongAgent start by writing
   a ping to the PingSpace.

  Usage:
    > compile.bat PongAgent.java

    Part of the application made up of:
       * PingPong.java
       * PingAgent.java
       * PongAgent.java
*/

import org.jspace.*;


public class PongAgent implements Runnable
{
  private Space pingSpace;
  private Space pongSpace;

  public PongAgent(Space ping, Space pong)
  {
    pingSpace = ping;
    pongSpace = pong;
  }


  public void run()
  {
    try {
      for (int i=0; i < 6; i++ ) {
        pingSpace.put("PING"+i);
        System.out.println("     PongAgent: put PING" + i + 
                                       "; waiting for PONG" + i);
        pongSpace.get(new ActualField("PONG"+i));
        System.out.println("     PongAgent: got PONG"+i);
      }
      System.out.println("     PongAgent DONE");
    }
    catch (InterruptedException e) 
    {  System.out.println("     PongAgent error: " + e);  }
  } /* run */

}  // end of PongAgent class
