
// PingAgent.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 PingAgent.java

    Part of the application made up of:
       * PingPong.java
       * PingAgent.java
       * PongAgent.java
*/

import org.jspace.*;


public class PingAgent implements Runnable
{
  private Space pingSpace;
  private Space pongSpace;


  public PingAgent(Space ping, Space pong)
  {
    pingSpace = ping;
    pongSpace = pong;
  }


  public void run()
  {
    try {
      for (int i=0; i < 6; i++) {
        System.out.println("PingAgent: waiting for PING" + i);
        pingSpace.get(new ActualField("PING"+i));
        System.out.println("PingAgent: got PING" + i + 
                                    "; putting PONG" + i);
        pongSpace.put("PONG"+i);
      }
      System.out.println("PingAgent DONE");
    }
    catch (InterruptedException e)
    {  System.out.println("PingAgent error: " + e);  }

  } /* run */

}  // end of PingAgent class
