[Go for Java programmers] Go programming 4 for Java developers

Source: Internet
Author: User
Document directory
  • Goroutines (go thread mechanism)
  • Channels (MPS Queue)
Go programming for Java developers

The original English text is here www. Nada. kth. se /~ Snilsson/go_for_java_programmers

Synchronized to www.waylau.com

Http://bbs.gocn.im/thread-89-1-1.html

======================= Connect to the text, the following body =

Panic and recover (fear and recovery)

panic(Panic) is a runtime error. Expand the goroutine stack, run any deferred function all the way, and then stop the program. Panic is similar to a Java exception, but only applicable to runtime errors, such as onenilPointer or try to index the array out of bounds. The Go program uses the built-inerrorType (see the preceding Section) to indicate events such as file termination.

You can use the built-inrecover(Recovery), regain control of the panic goroutine and resume normal operation. CallrecoverStop expansion and return input parameterspanic. Because only the code that is running is not expanded and contains a delay function,recoverThe function is valid only for the internal deferred function. If the goroutine is not panic,recoverReturnnil.

Go thread mechanism and pipeline goroutines (go thread mechanism)

GogoStart a new execution thread, goroutine. It runs in different, newly created goroutine. All goroutines in a program share the same address space.

Goroutines is lightweight and only occupies a little more space than stack allocation. Stack startup and growth requirements for allocating and releasing heap. The goroutines image reuse the coroutine of multiple operating system threads. You don't have to worry about these details.

go list.Sort()  // Run list.Sort in parallel; don’t wait for it. 

The go function for processing text.End, ProcessinggoVery powerful

func Publish(text string, delay time.Duration) {    go func() {        time.Sleep(delay)        fmt.Println(text)    }()  // Note the parentheses. We must call the function.}

VariabletextAnddelayShared between functions and function text. They exist as long as they are accessible.

Channels (MPS Queue)

The pipeline provides two goroutine synchronous execution and communication mechanisms through the value of the specified Element type.<-The operator specifies the Channel Direction, sending or receiving. If no direction is indicated, the channel is bidirectional.

chan T          // can be used to send and receive values of type Tchan<- float64  // can only be used to send float64s<-chan int      // can only be used to receive ints

A media transcoding queue is a reference type and is allocated using make.

ic := make(chan int)        // unbuffered channel of intswc := make(chan *Work, 10)  // buffered channel of pointers to Work

Use<-As a binary operator to send values on the pipeline. When a value is received in the pipeline, it is used as the unary operator.

ic <- 3       // Send 3 on the channel.work := <-wc  // Receive a pointer to Work from the channel.

If the pipeline is not buffered, the sender is blocked until the receiver receives the value. If the pipeline has a buffer, the sender is blocked until the value has been copied to the buffer. If the buffer is full, it means waiting until values are retrieved from some receivers. The receiver is blocked until data is received.

Concurrency (example)

Finally, we use an example to illustrate how to combine the scattered content. This is accepted by a server through a pipeline.WorkRequest example. Each request is run in a separate goroutine.WorkThe structure itself contains a pipeline to return a result.

package serverimport "log"// New creates a new server that accepts Work requests// through the req channel.func New() (req chan<- *Work) {    wc := make(chan *Work)    go serve(wc)    return wc}type Work struct {    Op    func(int, int) int    A, B  int    Reply chan int  // Server sends result on this channel.}func serve(wc <-chan *Work) {    for w := range wc {        go safelyDo(w)    }}func safelyDo(w *Work) {    // Regain control of panicking goroutine to avoid    // killing the other executing goroutines.    defer func() {        if err := recover(); err != nil {            log.Println("work failed:", err)        }    }()    do(w)}func do(w *Work) {    w.Reply <- w.Op(w.A, w.B)}
Server. Go

The following shows how to use it:

package server_testimport (    server "."    "fmt")func main() {    s := server.New()    divideByZero := &server.Work{        Op:    func(a, b int) int { return a / b },        A:     100,        B:     0,        Reply: make(chan int),    }    s <- divideByZero    add := &server.Work{        Op:    func(a, b int) int { return a + b },        A:     100,        B:     200,        Reply: make(chan int),    }    s <- add    fmt.Println(<-add.Reply)    // Output: 300}
Example_test.go

Concurrent Programming is a big topic. Java and go methods are completely different. To fully experience the fun of concurrent programming, read this share memory by communicating (share memory through communication).

Stefan Nilsson

This article is based on a similar article "C ++-oriented go programming"

======================== The full text is complete. Reprinted with the source ===============================

Http://download.csdn.net/detail/kkkloveyou/4991168 full text download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.