Are there any differences between a Go channel and a Java BlockingQueue? Both are queues with similar blocking and memory model semantics. Optionally both can have a capacity se
To do something similar to golang'select statement in java would involve using the java.nio package. Specifically selectors and channels. Check out the package docs here:
http://docs.oracle.com/javase/6/docs/api/java/nio/channels/package-summary.html#multiplex
It offers pretty much the same capability as the golang select statement, using a single thread to multiplex reading/writing from multiple channels.
One more very important difference is: You can close a Go channel to signal that no more elements are coming. That is not possible using Java.
Example: goroutine A reads a list of files. It posts each file into the Channel. After the last file, it closes the channel. goroutine B reads the files from the channel and processes them in some way. After the channel is closed, the goroutine quits.
Doing this in Java is not easily possible; however some workarounds exist.
I would say the biggest difference is that Go channels have support for the select
statement, which allow you to perform exactly one channel operation. An example (altered from the Go language specification):
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
}
In this example, exactly one of the receive-from-c1, send-to-c2, or receive-from-c3 operations will be performed. When entering the select, a ready channel (if any) is selected randomly. Otherwise, the operation blocks until one of the channels is ready.
I'm not aware of any trivial way to model this channel selection using the Java utilities. One could argue that this is a property of the select
statement rather than the design of channels, but I would argue that it's fundamental to the design of channels.
They can be used in similar ways.
The biggest differences are probably that go channels are considerably cheaper than a java object. and that go channels can be restricted to only send or only receive which can ensure some additional type enforcement regarding who can send and who can receive from a channel.