Channels in Logo

Channels in Go are similar to BlockingQueues in Java. They are used to connect concurrent threads. You can send values into BlockingQueues from one thread and receive those values in another thread.

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 with LinkedBlockingQueue
        // BlockingQueues are typed by the values they convey
        BlockingQueue<String> messages = new LinkedBlockingQueue<>();

        // Send a value into the BlockingQueue using the put() method
        // Here we send "ping" to the messages queue we made above, from a new thread
        new Thread(() -> {
            try {
                messages.put("ping");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // The take() method receives a value from the BlockingQueue
        // 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 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 BlockingQueue as an alternative to Go’s channels. The LinkedBlockingQueue implementation is used here, which is an optionally-bounded blocking queue based on linked nodes. The put() method is used to send a message, which will block if the queue is full. The take() method is used to receive a message, which will block if the queue is empty.

The concept of goroutines in Go is replaced with Java threads. We create a new thread to send the message asynchronously, similar to how a goroutine would work in Go.

This example demonstrates basic thread communication in Java using a BlockingQueue, which provides similar functionality to channels in Go for concurrent programming.