Channel Directions in Miranda
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ChannelDirections {
// This `ping` method only accepts a BlockingQueue 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 BlockingQueue 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 blocking queues as method parameters in Java, you can specify if a queue is meant to only send or receive values. This specificity increases the type-safety of the program.
In Java, we use BlockingQueue
interface to simulate channel-like behavior. The LinkedBlockingQueue
class is one implementation of this interface that we use in this example.
The ping
method only accepts a BlockingQueue
for sending values. It would be a compile-time error to try to receive from this queue in the method.
The pong
method accepts one BlockingQueue
for receives (pings
) and a second for sends (pongs
).
In the main
method, we create two BlockingQueue
instances, send a message through ping
, pass it through pong
, and finally print the received message.
To run the program:
$ javac ChannelDirections.java
$ java ChannelDirections
passed message
This example demonstrates how to use blocking queues in Java to achieve similar functionality to Go’s channel directions. While Java doesn’t have built-in channels like Go, the BlockingQueue
interface provides a way to implement similar patterns for concurrent communication between threads.