Channels in Squirrel

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

public class Channels {
    public static void main(String[] args) throws InterruptedException {
        // Create a new BlockingQueue. This is similar to a channel in Go.
        BlockingQueue<String> messages = new LinkedBlockingQueue<>();

        // Start a new thread to send a message.
        // This is similar to starting a goroutine in Go.
        new Thread(() -> {
            try {
                messages.put("ping");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // Receive the message from the queue and print it.
        String msg = messages.take();
        System.out.println(msg);
    }
}

Channels in Java are typically implemented using BlockingQueues. These provide a way for threads to communicate and synchronize their actions.

In this example, we’re using a LinkedBlockingQueue to create a channel-like structure. The BlockingQueue interface in Java provides methods that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

We create a new BlockingQueue with new LinkedBlockingQueue<>(). This queue will hold String values.

To send a value into the queue, we use the put() method. Here we send “ping” to the messages queue we made above, from a new thread. This is similar to using a goroutine in Go.

new Thread(() -> {
    try {
        messages.put("ping");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}).start();

To receive a value from the queue, we use the take() method. Here we’ll receive the “ping” message we sent above and print it out.

String msg = messages.take();
System.out.println(msg);

When we run the program, the “ping” message is successfully passed from one thread to another via our queue.

$ javac Channels.java
$ java Channels
ping

By default, put() and take() block until the operation can be completed. 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 BlockingQueue and threads to achieve similar functionality to Go’s channels and goroutines. While the syntax and specifics differ, the core concept of using queues for inter-thread communication remains the same.