Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go channel vs Java BlockingQueue

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 set.

like image 740
rrevo Avatar asked May 21 '12 18:05

rrevo


4 Answers

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.

like image 103
Brett Kail Avatar answered Nov 15 '22 01:11

Brett Kail


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.

like image 24
Kosta Avatar answered Nov 15 '22 03:11

Kosta


They can be used in similar ways.

  • Both can block on when putting/sending or taking/recieving.
  • Both have a capacity that governs when sending will block.

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.

like image 37
Jeremy Wall Avatar answered Nov 15 '22 02:11

Jeremy Wall


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.

like image 40
user2765592 Avatar answered Nov 15 '22 03:11

user2765592