
// RemoteDiningPhilosophers.java
// Michele Loreti and the jSpace Developers, 2017 
// Modified by Andrew Davison, ad@coe.psu.ac.th, May 2023

/* The Dining philosophers problem:
      https://en.wikipedia.org/wiki/Dining_philosophers_problem

  Original example at:
     https://github.com/pSpaces/jSpace/tree/master/examples/DiningPhilosophers/src/main/java/org/jspace/examples/df

  Usage:
    > compile.bat RemoteDiningPhilosophers.java
    > run.bat RemoteDiningPhilosophers

    Part of the application made up of:
       * RemoteDiningPhilosophers.java
       * Philosopher.java

  Other versions: 
    * DiningPhilosophers.java
    * DiningPhilTickets.java
*/


import java.io.*;
import java.net.*;

import org.jspace.*;


public class RemoteDiningPhilosophers
{

  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/table?keep";

  private static final int NUM_PHILS = 5;


  public static void main( String[] argv ) 
                 throws InterruptedException,
                        UnknownHostException, IOException
  {
    SpaceRepository repository = new SpaceRepository();
    repository.addGate(GATE_URI);
    repository.add("table", new VisSpace());
    // repository.add("table", new SequentialSpace());

    System.out.println("Placing " + NUM_PHILS + 
                                  " forks on the table...");
    for( int i=0; i < NUM_PHILS; i++)
      repository.put("table","FORK",i);

    PrintAreas pas = new PrintAreas(NUM_PHILS);

    Thread[] philosophers = new Thread[NUM_PHILS];
    for( int i=0; i < NUM_PHILS; i++ ) {
      philosophers[i] = new Thread( 
         new Philosopher(i, pas, new RemoteSpace(REMOTE_URI), 
                             i, (i+1)%NUM_PHILS),
         "PHIL-"+i);
      philosophers[i].start();
    }

    SpaceUtils.waitTerminated(philosophers);
        /* MUST be included or main() will terminate 
           before the remote threads have even started
        */
    repository.shutDown();
  } /* main */


}  // end of RemoteDiningPhilosophers class
