How are coroutines implemented in JVM langs without JVM support?

前端 未结 4 758
醉话见心
醉话见心 2020-12-23 13:28

This question came up after reading the Loom proposal, which describes an approach of implementing coroutines in the Java programming language.

Particularly this pro

4条回答
  •  盖世英雄少女心
    2020-12-23 14:09

    Coroutines do not rely on features of the operating system or the JVM. Instead, coroutines and suspend functions are transformed by the compiler producing a state machine capable of handling suspensions in general and passing around suspending coroutines keeping their state. This is enabled by Continuations, which are added as a parameter to each and every suspending function by the compiler; this technique is called “Continuation-passing style”(CPS).

    One example can be observed in the transformation of suspend functions:

    suspend fun  CompletableFuture.await(): T
    

    The following shows its signature after CPS transformation:

    fun  CompletableFuture.await(continuation: Continuation): Any?
    

    If you want to know the hard details, you need to read this explanation.

提交回复
热议问题