
// RemoteProducerConsumer.java
// Michele Loreti and the jSpace Developers, 2017
// Modified by Andrew Davison, ad@coe.psu.ac.th, May 2023

/* Have two producer threads each send NUM_ITEMS items
   to a single consumer thread via a remote tuple space.

   When VisSpace draws queries and tuples, it includes the
   name of the threads responsible. However for a remote space,
   it displays the thread names of the remote threads
   rather than the thread names created by the programmer 
   (i.e. "Producer-0", "Producer-1", "Consumer").

  Original example at:
    https://github.com/pSpaces/jSpace/tree/master/examples/ProducerConsumer/src/main/java/org/jspace/examples/pc

  Usage:
    > compile.bat RemoteProducerConsumer.java
    > run.bat RemoteProducerConsumer

    Part of the application made up of:
       * RemoteProducerConsumer.java
       * ProducerAgent.java
       * ConsumerAgent.java

  Other version: 
    * ProducerConsumer.java
*/


import java.io.*;
import java.net.*;

import org.jspace.*;


public class RemoteProducerConsumer
{
  private static final int NUM_ITEMS = 10;

  private final static String GATE_URI = 
                  "tcp://127.0.0.1:9001/?keep";

  private final static String REMOTE_URI = 
                  "tcp://127.0.0.1:9001/aspace?keep";
     // make sure the space name matches that in SpaceRepository.add()


  public static void main( String[] argv ) 
                   throws InterruptedException,
                          UnknownHostException, IOException
  {
    SpaceRepository repository = new SpaceRepository();
    repository.addGate(GATE_URI);
    // choose one of these spaces:
    repository.add("aspace", new VisSpace(1000));
    // repository.add("aspace", new SequentialSpace());

    Thread t1 = new Thread( 
       new ProducerAgent(0, "hammer", 
          new RemoteSpace(REMOTE_URI), NUM_ITEMS),
             "Producer-0");

    Thread t2 = new Thread( 
       new ProducerAgent(1, "anvil", 
          new RemoteSpace(REMOTE_URI), NUM_ITEMS),
             "Producer-1");

    Thread t3 = new Thread( 
       new ConsumerAgent(
          new RemoteSpace(REMOTE_URI), NUM_ITEMS*2),
             "Consumer");

     /* Note: each thread creates its own reference to the
        remote space. This ensues they each has their own
        gate to the space. 
     */
    t3.start();
    t1.start();
    t2.start();

    SpaceUtils.waitTerminated(t1, t2, t3);
    repository.shutDown();
  } /* main */

}  // end of RemoteProducerConsumer class
