Go channel vs Java BlockingQueue

后端 未结 4 747
日久生厌
日久生厌 2021-02-01 23:55

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

4条回答
  •  半阙折子戏
    2021-02-02 00:18

    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.

提交回复
热议问题