Go channel vs Java BlockingQueue

Are there any differences between Go channel and Java BlockingQueue? Both are queues with similar locking and semantics of the memory model. If desired, both may have a capacity.

+7
source share
4 answers

I would say that the biggest difference is that Go channels support the select statement, which allows you to perform exactly one operation on the channel. Example (modified from 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, only one of the receive-from-c1, send-c2, or receive-c-c3 operations will be performed. When you enter a selection, an arbitrary channel is selected (if any). Otherwise, the operation is blocked until one of the channels is ready.

I am not aware of any trivial way of modeling the selection of this channel using the Java utility. It can be argued that this is a property of the select statement, not a channel design, but I would say that it is fundamental to channel design.

+12
source

Another very important difference: you can close the Go channel to signal that there will be no more elements. This is not possible with Java.

Example: goroutine A reads a list of files. It puts each file in the channel. After the last file, it closes the channel. goroutine B reads files from the channel and somehow processes them. After the channel is closed, goroutin is closed.

Doing this in Java is not easy; however, there are some workarounds.

+5
source

They can be used in a similar way.

  • Both can be blocked when sending / sending or receiving / receiving.
  • Both have a capacity that controls when sending will be blocked.

The biggest differences are probably that the channels go much cheaper than the java object. and these channels can be limited only by sending or only receiving, which can provide some additional coercion such as who can send and who can receive from the channel.

+3
source

To do something like the golang'select statement in java, the java.nio package will be involved. In particular, the selector 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 almost the same functionality as the golang select statement, using a single stream for multiplex read / write from multiple channels.

+3
source

All Articles