Channels in Minitab
import java.util.concurrent.*;
public class Channels {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Create a new BlockingQueue with a capacity of 1
// BlockingQueue is similar to channels in concept
BlockingQueue<String> messages = new ArrayBlockingQueue<>(1);
// Send a value into the queue using a new thread
// This is similar to sending a value into a channel using a goroutine
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
try {
messages.put("ping");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// Receive a value from the queue and print it out
// This is similar to receiving a value from a channel
String msg = messages.take();
System.out.println(msg);
executor.shutdown();
}
}
BlockingQueues in Java are similar to channels in concept. They allow communication between different threads. You can send values into a BlockingQueue from one thread and receive those values in another thread.
Create a new BlockingQueue with new ArrayBlockingQueue<>(capacity)
. BlockingQueues are typed by the values they convey.
Send a value into a BlockingQueue using the put()
method. Here we send "ping"
to the messages
queue we made above, from a new thread.
The take()
method receives a value from the BlockingQueue. Here we’ll receive the "ping"
message we sent above and print it out.
When we run the program, the "ping"
message is successfully passed from one thread to another via our BlockingQueue.
$ javac Channels.java
$ java Channels
ping
By default, put()
and take()
methods block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the "ping"
message without having to use any other synchronization.
In Java, we use ExecutorService
to manage threads, which is somewhat similar to how goroutines are used in other languages. The BlockingQueue
provides the channel-like behavior for communication between threads.