Non Blocking Channel Operations in Miranda
Our example demonstrates non-blocking channel operations using Java’s BlockingQueue
interface and the offer
and poll
methods with timeouts. While Java doesn’t have built-in channels like Go, we can achieve similar functionality using concurrent collections.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class NonBlockingOperations {
public static void main(String[] args) {
BlockingQueue<String> messages = new LinkedBlockingQueue<>();
BlockingQueue<Boolean> signals = new LinkedBlockingQueue<>();
// Here's a non-blocking receive. If a value is
// available in `messages` then `poll` will return
// that value. If not, it will immediately return null.
String msg = messages.poll();
if (msg != null) {
System.out.println("received message " + msg);
} else {
System.out.println("no message received");
}
// A non-blocking send works similarly. Here `msg`
// cannot be sent to the `messages` queue if it's full.
// The `offer` method will return false if the element
// cannot be added.
msg = "hi";
if (messages.offer(msg)) {
System.out.println("sent message " + msg);
} else {
System.out.println("no message sent");
}
// We can use multiple conditions to implement a multi-way
// non-blocking select. Here we attempt non-blocking receives
// on both `messages` and `signals`.
String receivedMsg = messages.poll();
Boolean receivedSignal = signals.poll();
if (receivedMsg != null) {
System.out.println("received message " + receivedMsg);
} else if (receivedSignal != null) {
System.out.println("received signal " + receivedSignal);
} else {
System.out.println("no activity");
}
}
}
In this Java implementation:
We use
BlockingQueue<String>
andBlockingQueue<Boolean>
instead of channels.LinkedBlockingQueue
is used as the concrete implementation.The
poll()
method is used for non-blocking receives. It immediately returnsnull
if the queue is empty.The
offer(E e)
method is used for non-blocking sends. It returnsfalse
if the element cannot be added to the queue (e.g., if the queue is full).To simulate a multi-way select, we use multiple
if-else
conditions checking the results ofpoll()
on different queues.
This code demonstrates how to perform non-blocking operations in Java, which is conceptually similar to non-blocking channel operations in other languages. The BlockingQueue
interface provides additional methods like offer(E e, long timeout, TimeUnit unit)
and poll(long timeout, TimeUnit unit)
for operations with timeouts, which can be useful in more complex scenarios.
To run this program:
$ javac NonBlockingOperations.java
$ java NonBlockingOperations
no message received
no message sent
no activity
This output shows that no messages were available in the queues, demonstrating the non-blocking nature of the operations.