0

I need to implement vector clocks in a small programming exercise and I decided to use Java for it. My question is not related to the actual algorithm of manipulating the vector clocks of processes, but how to initialize other Java applications or child processes relatively easy from another Java program?

My initial plan is the following: I have a "main program", which decides how many clients/children to start and then these children/clients should communicate with each other and update their corresponding vector clocks accordingly. The number of clients to be started depends on the number of lines in a certain input file given to the "main program". What is the most elegant way to start these client processes? They should each take two files and an integer as parameters. The files tell what to do (send or advance clock) and the integer tells from which line in a configuration file the client should pick its port number to be used.

treiman
  • 59
  • 1
  • 6
  • Whether to use threads or some exec() variation of Java or something else similar. I haven't previously done anything that requires concurrent operation. Also, I fear that I might have a problem if the clients start reading their input and acting on it before each client is initialized. Is this prevented easily? – treiman Feb 09 '11 at 11:50
  • Use something like a countdown latch (java.util.concurrent.CountDownLatch) to make sure that the threads don't start too early – Erik Feb 09 '11 at 12:29

2 Answers2

2

In java, the concept of creating concurrent tasks is based on threads rather than processes. To start a new process, you must typically invoke java multiple times or use the ProcessBuilder interface. Concurrency in java is designed for threads, so that's what I'll recommend you to try, e.g.,:

public static void main(String[] args) {
    int numberOfThreads  = ...
    for(int i = 0; i < numberOfThreads; i++) {
        File f1 = ...
        File f2 = .... 
        int j = ... 

        new Thread(new VectorClock(f1, f2, j)).start();
    }
}

public class VectorClock implements Runnable {
    public VectorClock(File file1, File file2, int i) {
       // ...
    }

    @Override
    public void run() {
        // this gets executed when invoked by a threads .start() routine
    }
}
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • If you want to make sure that all threads are initialized before the first starts running, you can create a Thread[] and include an extra loop afterwards that calls start() for all threads (you'll need the array anyhow for an easy way to figure out when all threads have finished) – Voo Feb 10 '11 at 22:43
0

Have a look at this answer for C-like forks in Java.

Community
  • 1
  • 1
goncalossilva
  • 1,830
  • 15
  • 25