Channels in Java
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. BlockingQueues are similar to channels
// in that they allow for thread-safe communication between threads.
BlockingQueue<String> messages = new LinkedBlockingQueue<>();
// Start a new thread to send a message.
// This is similar to using 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.
// This will block until a message is available.
String msg = messages.take();
System.out.println(msg);
}
}
In Java, we don’t have built-in channels like in Go, but we can use BlockingQueue
to achieve similar functionality. BlockingQueue
is part of Java’s concurrent collections and provides thread-safe operations for adding and removing elements.
Here’s how the code works:
We create a
BlockingQueue<String>
calledmessages
. This queue will hold our messages.We start a new thread using
new Thread(() -> {...}).start()
. This is similar to using a goroutine in Go. Inside this thread, we put the string “ping” into the queue usingmessages.put("ping")
.In the main thread, we use
messages.take()
to receive a message from the queue. This operation will block until a message is available, similar to receiving from a channel in Go.Finally, we print the received message.
When we run the program, the “ping” message is successfully passed from one thread to another via our blocking queue.
$ javac Channels.java
$ java Channels
ping
By default, put
and take
operations on a BlockingQueue
block until they 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 mechanism.
While Java’s BlockingQueue
isn’t exactly the same as Go’s channels, it provides a similar way to safely communicate between concurrent threads.