协程(coroutine)这个词其实有很多叫法,比如有的人喜欢称为纤程(fiber),或者绿色线程(greenthread)。其实究其本质,对于协程最直观的解释是线程的线程。虽然读上去有点拗口,但本质上就是这样。
协程的核心在于调度那块由他来负责解决,遇到阻塞操作,立刻放弃掉,并且记录当前栈上的数据,阻塞完后立刻再找一个线程恢复栈并把阻塞的结果放到这个线程上去跑,这样看上去好像跟写同步代码没有任何差别,这整个流程可以称为coroutine,而跑在由coroutine负责调度的线程称为fiber。
java协程的实现
早期,在jvm上实现协程一般会使用kilim,不过这个工具已经很久不更新了,现在常用的工具是quasar,而本文章会全部基于quasar来介绍。
下面尝试通过quasar来实现类似于go语言的coroutine以及channel。
为了能有明确的对比,这里先用go语言实现一个对于10以内自然数分别求平方的例子。
func counter(out chan<- int) {
for x := 0; x < 10; x++ {
out <- x
}
close(out)
}
func squarer(out chan<- int, in <-chan int) {
for v := range in {
out <- v * v
}
close(out)
}
func printer(in <-chan int) {
for v := range in {
fmt.println(v)
}
}
func main() {
//定义两个int类型的channel
naturals := make(chan int)
squares := make(chan int)
//产生两个fiber,用go关键字
go counter(naturals)
go squarer(squares, naturals)
//获取计算结果
printer(squares)
}
上面这个例子,通过channel两解耦两边的数据共享。对于这个channel,大家可以理解为java里的synchronousqueue。下面我直接上quasar版java代码的,几乎可以原封不动的复制go语言的代码。
public class example {
private static void printer(channel<integer> in) throws suspendexecution, interruptedexception {
integer v;
while ((v = in.receive()) != null) {
system.out.println(v);
}
}
public static void main(string[] args) throws executionexception, interruptedexception, suspendexecution {
//定义两个channel
channel<integer> naturals = channels.newchannel(-1);
channel<integer> squares = channels.newchannel(-1);
//运行两个fiber实现.
new fiber(() -> {
for (int i = 0; i < 10; i++)
naturals.send(i);
naturals.close();
}).start();
new fiber(() -> {
integer v;
while ((v = naturals.receive()) != null)
squares.send(v * v);
squares.close();
}).start();
printer(squares);
}
}
两者对比,看上去java似好像更复杂些,没办法这就是java的风格,而且这还是通过第三方的库来实现的。
说到这里各位肯定对fiber很好奇了。也许你会表示怀疑fiber是不是如上面所描述的那样,下面我们尝试用quasar建立一百万个fiber,看看内存占用多少,我先尝试了创建百万个thread。
for (int i = 0; i < 1_000_000; i++) {
new thread(() -> {
try {
thread.sleep(10000);
} catch (interruptedexception e) {
e.printstacktrace();
}
}).start();
}
很不幸,直接报exception in thread "main" java.lang.outofmemoryerror: unable to create new native thread,这是情理之中的。下面是通过quasar建立百万个fiber。
public static void main(string[] args) throws executionexception, interruptedexception, suspendexecution {
int fibernumber = 1_000_000;
countdownlatch latch = new countdownlatch(1);
atomicinteger counter = new atomicinteger(0);
for (int i = 0; i < fibernumber; i++) {
new fiber(() -> {
counter.incrementandget();
if (counter.get() == fibernumber) {
system.out.println("done");
}
strand.sleep(1000000);
}).start();
}
latch.await();
}
我这里加了latch,阻止程序跑完就关闭,strand.sleep其实跟thread.sleep一样,只是这里针对的是fiber。
最终控制台是可以输出done的,说明程序已经创建了百万个fiber,设置sleep是为了让fiber一直运行,从而方便计算内存占用。官方宣称一个空闲的fiber大约占用400byte,那这里应该是占用400mb堆内存,但是这里通过jmap -heap pid显示大约占用了1000mb,也就是说一个fiber占用1kb。
quasar是怎么实现fiber的
其实quasar实现的coroutine的方式与go语言很像,只不过前者是使用框架来实现,而go语言则是语言内置的功能。
不过如果你熟悉了go语言的调度机制的话,那么对于quasar的调度机制就会好理解很多了,因为两者有很多相似之处。
quasar里的fiber其实是一个continuation,他可以被quasar定义的scheduler调度,一个continuation记录着运行实例的状态,而且会被随时中断,并且也会随后在他被中断的地方恢复。
quasar其实是通过修改bytecode来达到这个目的,所以运行quasar程序的时候,你需要先通过java-agent在运行时修改你的代码,当然也可以在编译期间这么干。go语言的内置了自己的调度器,而quasar则是默认使用forkjoinpool这个具有work-stealing功能的线程池来当调度器。work-stealing非常重要,因为你不清楚哪个fiber会先执行完,而work-stealing可以动态的从其他的等等队列偷一个context过来,这样可以最大化使用cpu资源。
那这里你会问了,quasar怎么知道修改哪些字节码呢,其实也很简单,quasar会通过java-agent在运行时扫描哪些方法是可以中断的,同时会在方法被调用前和调度后的方法内插入一些continuation逻辑,如果你在方法上定义了@suspendable注解,那quasar会对调用该注解的方法做类似下面的事情。
这里假设你在方法f上定义了@suspendable,同时去调用了有同样注解的方法g,那么所有调用f的方法会插入一些字节码,这些字节码的逻辑就是记录当前fiber栈上的状态,以便在未来可以动态的恢复。(fiber类似线程也有自己的栈)。在suspendable方法链内fiber的父类会调用fiber.park,这样会抛出suspendexecution异常,从而来停止线程的运行,好让quasar的调度器执行调度。这里的suspendexecution会被fiber自己捕获,业务层面上不应该捕获到。如果fiber被唤醒了(调度器层面会去调用fiber.unpark),那么f会在被中断的地方重新被调用(这里fiber会知道自己在哪里被中断),同时会把g的调用结果(g会return结果)插入到f的恢复点,这样看上去就好像g的return是f的local variables了,从而避免了callback嵌套。
上面说了一大堆,其实简单点来讲就是,想办法让运行中的线程栈停下来,然后让quasar的调度器介入。
jvm线程中断的条件有两个:
1、抛异常
2、return。
而在quasar中,一般就是通过抛异常的方式来达到的,所以你会看到上面的代码会抛出suspendexecution。但是如果你真捕获到这个异常,那就说明有问题了,所以一般会这么写。
@suspendable
public int f() {
try {
// do some stuff
return g() * 2;
} catch(suspendexecution s) {
//这里不应该捕获到异常.
throw new assertionerror(s);
}
}
相关阅读:
java微课——像玩游戏般学习java