Java Async IO Library: Quasar (use Channel)

前言

你若是熟悉go ,fiber (對於fiber能夠簡單理解成爲輕量級線程)和 channel 就對應go 的goroutines 和channel,在go語言中用法以下:html

package main

import "fmt"

func sum(s []int, c chan int) {   //方法執行體
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // send sum to c
}

func main() {                      //main 函數
	s := []int{7, 2, 8, -9, 4, 0}     // 構建一個數組

	c := make(chan int)    //新建一個channel
	go sum(s[:len(s)/2], c)  // 新起一個協程,而後在協程中執行方法,至關於new 一個fiber
	go sum(s[len(s)/2:], c)  // new 一個fiber 。。
	x, y := <-c, <-c // receive from c    // 經過channel來傳遞消息

	fmt.Println(x, y, x+y)
}

fiber example:java

Channel<Object> objectChannel = Channels.newChannel(0);  // 0 ,receive() block until send() complete
new Fiber<Void>((SuspendableRunnable) () -> {
            // your code
            objectChannel.send()

        }).inheritThreadLocals().start();

// 簡化成java8 functional://todo

什麼是channel

channel 用於提供不一樣fiber之間的交互,保證同一時間只有一個fiber能訪問到值。golang

channel 最主要的兩個方法send() and receive(),send() 會阻塞直到結果完成,receive()會阻塞直至send()操做完成。(也正是由於阻塞,因此和fiber(輕量)配合得很好)編程

BufferChannel ,new channel 的時候指定大小,buffer滿的時候會阻塞。數組

why not use fiber.get()? throw null pointer exception, (how about strand?)app

quasar 的fiber提供個get()方法,但在實際交互過程當中會存在@suspendable 忘了的狀況(交互多的時候比較複雜)函數

爲何要使用channel

Instead of explicitly using locks to mediate access to shared data, Go encourages the use of channels to pass references to data between goroutines. This approach ensures that only one goroutine has access to the data at a given time. The concept is summarized in the document Effective Go (a must-read for any Go programmer): Do not communicate by sharing memory; instead, share memory by communicating.線程

比起傳統的經過加鎖的方式訪問變量,fiber經過消息傳遞的方式來共享變量code

channel 更像是queue,經過這種方式來共享消息,這種編程方式的原理的話參考這篇論文CSP協程

總結

fiber 和channel構建起來的編程模型,簡單理解就是,起一個協程(輕量級線程),它們之間的交互經過channel來傳遞消息。

參考:

share memory by communicate code walk

share memory by communicate blog

effective go

相關文章
相關標籤/搜索