-1

I have below example of concurrency channels from GoByExamples

Is there something equivalent in Java? I would have thought it would be much more verbose to implement the same thing.

// Basic sends and receives on channels are blocking.
// However, we can use `select` with a `default` clause to
// implement _non-blocking_ sends, receives, and even
// non-blocking multi-way `select`s.

package main

import "fmt"

func main() {
    messages := make(chan string)
    signals := make(chan bool)

    // Here's a non-blocking receive. If a value is
    // available on `messages` then `select` will take
    // the `<-messages` `case` with that value. If not
    // it will immediately take the `default` case.
    select {
    case msg := <-messages:
        fmt.Println("received message", msg)
    default:
        fmt.Println("no message received")
    }

    // A non-blocking send works similarly.
    msg := "hi"
    select {
    case messages <- msg:
        fmt.Println("sent message", msg)
    default:
        fmt.Println("no message sent")
    }

    // We can use multiple `case`s above the `default`
    // clause to implement a multi-way non-blocking
    // select. Here we attempt non-blocking receives
    // on both `messages` and `signals`.
    select {
    case msg := <-messages:
        fmt.Println("received message", msg)
    case sig := <-signals:
        fmt.Println("received signal", sig)
    default:
        fmt.Println("no activity")
    }
}
Passionate Engineer
  • 10,034
  • 26
  • 96
  • 168
  • 1
    *Is there something equivalent in Java?* Yes. *I would have thought it would be much more verbose to implement the same thing.* Quite possibly. My hourly rates are really almost unbelievably reasonable if you'd like to find out for sure... – Elliott Frisch Jan 21 '15 at 05:43
  • Technically yes, although I'm not going to do it :-) have a look at http://www.ibm.com/developerworks/library/j-csp1/index.html (there are also parts 2 and 3, llinked from that doc) Also http://www.cs.kent.ac.uk/projects/ofa/jcsp/ and wikipedia article on the same http://en.wikipedia.org/wiki/JCSP . – Intermernet Jan 21 '15 at 05:43
  • 1
    This would be a good starting point: http://stackoverflow.com/questions/22561110/equivalent-of-golang-channel-in-java – Anupam Saini Jan 21 '15 at 06:12

1 Answers1

0

Select statement is the reason to introduce concurrency at language syntax level in Go. Concurrent function call can (and usually done) be implemented on library level with helper function like spawn( function()) and channels just as data structures with mutex or lock in most other languages. But select statement can't.

Uvelichitel
  • 8,220
  • 1
  • 19
  • 36