Stuck writing to JCSP channel

So I learned about BlockingQueue and its implementation SynchronousQueue. As stated here, SynchronousQueue works in similar way in which CSP Channels work. This helped me realize what was wrong with my code. Simply put, you can't write and read from channel in same process. Channel is way for processes to communicate.

Similarly to SynchronousQueue's put() which will wait for other process to call take(), CSP Channel's write() which will wait for corresponding read() to be called. The difference is that CSP Channels have objects ChannelOutput and ChannelInput through which objects are written and red. Conversely, you can call put and take directly on instance of SynchronousQueue. Personally, I find SynchronousQueue much easier to understand, which probably relates to JCSP not being very popular.

Still, if you're interested how I made the above code work in JCSP, here it is:

public static class Process1 implements CSProcess {

    private ChannelOutputInt output;

    public Process1(ChannelOutputInt out) {
        output = out;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1; i++) {
            System.out.println("Written...");
            output.write(5);
        }
        output.write(-1);
    }

}

public static class Process2 implements CSProcess {

    private ChannelInputInt input;

    public Process2(ChannelInputInt in) {
        input = in;
    }

    @Override
    public void run() {
        int x = 0;
        while ((x = input.read()) > 0) {
            System.out.println(x);
        }
    }

}

public static void main(String[] args) {

    One2OneChannelInt chan = Channel.one2oneInt();

    Process1 process1 = new Process1(chan.out());
    Process2 process2 = new Process2(chan.in());

    Parallel parallel = new Parallel();

    parallel.addProcess(process1);
    parallel.addProcess(process2);
    parallel.run();
}

Tags:

Java

Channel