Equivalent of Go Channel in Java
Question:
I need to efficiently read data from multiple blocking queues without creating separate reader threads. Is there an equivalent mechanism to Go's select/epoll in Java?
Answer:
Consider using the JCSP library, which provides the Alternative class. Alternative is comparable to Go's select statement. It enables you to create a single consumer thread that can multiplex data from multiple source channels without the need for constant polling.
Advantages of JCSP Alternative:
Usage Example:
The following Java code demonstrates a fair multiplexer using JCSP:
import org.jcsp.lang.*; public class FairPlex implements CSProcess { private final AltingChannelInput[] in; private final ChannelOutput out; public FairPlex (final AltingChannelInput[] in, final ChannelOutput out) { this.in = in; this.out = out; } public void run () { final Alternative alt = new Alternative (in); while (true) { final int index = alt.fairSelect (); out.write (in[index].read ()); } } }
Additional Note:
The current version of JCSP in the Maven repositories is 1.1-rc5, contrary to what is stated on the JCSP website.
The above is the detailed content of Is There a Java Equivalent to Go's `select` for Efficiently Reading from Multiple Blocking Queues?. For more information, please follow other related articles on the PHP Chinese website!