Channel Directions in Karel

In Java, we can use the BlockingQueue interface to achieve a similar concept to channel directions. The BlockingQueue interface provides thread-safe operations for adding and removing elements, which can be used for inter-thread communication.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ChannelDirections {

    // This ping method only accepts a queue for sending values.
    // It would be a compile-time error to try to receive from this queue.
    public static void ping(BlockingQueue<String> pings, String msg) throws InterruptedException {
        pings.put(msg);
    }

    // The pong method accepts one queue for receives (pings) and a second for sends (pongs).
    public static void pong(BlockingQueue<String> pings, BlockingQueue<String> pongs) throws InterruptedException {
        String msg = pings.take();
        pongs.put(msg);
    }

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> pings = new LinkedBlockingQueue<>(1);
        BlockingQueue<String> pongs = new LinkedBlockingQueue<>(1);

        ping(pings, "passed message");
        pong(pings, pongs);
        System.out.println(pongs.take());
    }
}

When using BlockingQueues as method parameters, we can specify if a queue is meant to only send or receive values by using the appropriate interface methods. This specificity increases the type-safety of the program.

The ping method only accepts a queue for sending values. It would be a compile-time error to try to receive on this queue within the method.

The pong method accepts one queue for receives (pings) and a second for sends (pongs).

In the main method, we create two BlockingQueues, pings and pongs, each with a capacity of 1. We then call the ping method to send a message, followed by the pong method to receive from pings and send to pongs. Finally, we print the received message from pongs.

To run the program:

$ javac ChannelDirections.java
$ java ChannelDirections
passed message

This example demonstrates how to use BlockingQueues in Java to achieve a similar behavior to channel directions in other languages, allowing for type-safe, directional communication between threads.