In Java, we don’t have built-in channels like in some other languages. However, we can simulate similar behavior using BlockingQueue from the java.util.concurrent package. We’ll use ArrayBlockingQueue for this example.
In this example, we use ArrayBlockingQueue to simulate channels. The BlockingQueue interface 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 worker thread that continuously takes jobs from the jobs queue. To signal that no more jobs will be sent, we send a null value, which the worker interprets as a signal to finish.
The main thread sends three jobs to the worker, then sends a null to indicate it’s finished. It then waits for the worker to signal completion by taking from the done queue.
After the worker has finished, we attempt to take another job from the jobs queue. Since the queue is empty (and we’re using poll() which doesn’t block), this returns null immediately.
To run this program:
This example demonstrates how to simulate channel-like behavior in Java using BlockingQueue. While it’s not identical to channel closing in some other languages, it achieves a similar effect of signaling completion to a worker thread.