协程的挂起是个很重要也比较难懂的概念。
从协程的启动开始讲起。
@Test
fun 测试协程启动() {
GlobalScope.launch(start = CoroutineStart.DEFAULT) 协程启动的地方@
{
val 挂起方法的值 = 挂起方法("测试")
println(挂起方法的值)
}
}
suspend fun 挂起方法(参数: String): String {
kotlinx.coroutines.delay(200)
return 参数
}
下面看一下调用逻辑:
如果你按照这个路径去找对应的方法实现,我相信你会提出几个疑问:
1,(suspend R.() -> T)这个东东是什么?
答:
想要更加深入了解它我们得看看字节码了。(不懂字节码的朋友可以点击这儿)
public final 测试协程启动()V
@Lorg/junit/Test;()
L0
LINENUMBER 16 L0
GETSTATIC kotlinx/coroutines/GlobalScope.INSTANCE : Lkotlinx/coroutines/GlobalScope;
CHECKCAST kotlinx/coroutines/CoroutineScope
ACONST_NULL
GETSTATIC kotlinx/coroutines/CoroutineStart.DEFAULT : Lkotlinx/coroutines/CoroutineStart;
L1
LINENUMBER 17 L1
NEW com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1
DUP
ALOAD 0
ACONST_NULL
INVOKESPECIAL com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.<init> (Lcom/example/dugup/gbd/ExampleUnitTest;Lkotlin/coroutines/Continuation;)V
CHECKCAST kotlin/jvm/functions/Function2
ICONST_1
ACONST_NULL
L2
LINENUMBER 16 L2
INVOKESTATIC kotlinx/coroutines/BuildersKt.launch$default (Lkotlinx/coroutines/CoroutineScope;Lkotlin/coroutines/CoroutineContext;Lkotlinx/coroutines/CoroutineStart;Lkotlin/jvm/functions/Function2;ILjava/lang/Object;)Lkotlinx/coroutines/Job;
POP
L3
LINENUMBER 21 L3
RETURN
L4
LOCALVARIABLE this Lcom/example/dugup/gbd/ExampleUnitTest; L0 L4 0
MAXSTACK = 7
MAXLOCALS = 1
我们看看它做了什么:
a,获取了GlobalScope.INSTANCE,CoroutineStart.DEFAULT
b,创建com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1对象
c,调用kotlinx/coroutines/BuildersKt.launch$default启动协程
tip:BuildersKt.launch$default可以在把BuildersKt反编译成Java文件之后找到
// $FF: synthetic method
public static Job launch$default(CoroutineScope var0, CoroutineContext var1, CoroutineStart var2, Function2 var3, int var4, Object var5) {
return BuildersKt__Builders_commonKt.launch$default(var0, var1, var2, var3, var4, var5);
}
再看看com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1是个啥?
final class com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1 extends kotlin/coroutines/jvm/internal/SuspendLambda implements kotlin/jvm/functions/Function2 {
// access flags 0x2
private Lkotlinx/coroutines/CoroutineScope; p$
// access flags 0x11
public final invokeSuspend(Ljava/lang/Object;)Ljava/lang/Object;
L0
INVOKESTATIC kotlin/coroutines/intrinsics/IntrinsicsKt.getCOROUTINE_SUSPENDED ()Ljava/lang/Object;
L1
LINENUMBER 17 L1
ASTORE 5
ALOAD 0
GETFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.label : I
TABLESWITCH
0: L2
1: L3
default: L4
L2
ALOAD 1
INVOKESTATIC kotlin/ResultKt.throwOnFailure (Ljava/lang/Object;)V
L5
ALOAD 0
GETFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.p$ : Lkotlinx/coroutines/CoroutineScope;
ASTORE 2
L6
LINENUMBER 18 L6
ALOAD 0
GETFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.this$0 : Lcom/example/dugup/gbd/ExampleUnitTest;
LDC "\u6d4b\u8bd5"
ALOAD 0
ALOAD 0
ALOAD 2
PUTFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.L$0 : Ljava/lang/Object;
ALOAD 0
ICONST_1
PUTFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.label : I
INVOKEVIRTUAL com/example/dugup/gbd/ExampleUnitTest.挂起方法 (Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
L7
DUP
ALOAD 5
IF_ACMPNE L8
L9
LINENUMBER 17 L9
ALOAD 5
ARETURN
L3
ALOAD 0
GETFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.L$0 : Ljava/lang/Object;
CHECKCAST kotlinx/coroutines/CoroutineScope
ASTORE 2
L10
ALOAD 1
INVOKESTATIC kotlin/ResultKt.throwOnFailure (Ljava/lang/Object;)V
ALOAD 1
L8
CHECKCAST java/lang/String
ASTORE 3
L11
LINENUMBER 19 L11
L12
ICONST_0
ISTORE 4
L13
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ALOAD 3
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/Object;)V
L14
L15
LINENUMBER 20 L15
GETSTATIC kotlin/Unit.INSTANCE : Lkotlin/Unit;
ARETURN
L4
NEW java/lang/IllegalStateException
DUP
LDC "call to 'resume' before 'invoke' with coroutine"
INVOKESPECIAL java/lang/IllegalStateException.<init> (Ljava/lang/String;)V
ATHROW
L16
LOCALVARIABLE $this$协程启动的地方 Lkotlinx/coroutines/CoroutineScope; L6 L4 2
LOCALVARIABLE 挂起方法的值 Ljava/lang/String; L11 L15 3
LOCALVARIABLE this Lcom/example/dugup/gbd/ExampleUnitTest$测试协程启动$1; L0 L16 0
LOCALVARIABLE $result Ljava/lang/Object; L0 L16 1
MAXSTACK = 5
MAXLOCALS = 6
// access flags 0x0
Ljava/lang/Object; L$0
// access flags 0x0
<init>(Lcom/example/dugup/gbd/ExampleUnitTest;Lkotlin/coroutines/Continuation;)V
ALOAD 0
ALOAD 1
PUTFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.this$0 : Lcom/example/dugup/gbd/ExampleUnitTest;
ALOAD 0
ICONST_2
ALOAD 2
INVOKESPECIAL kotlin/coroutines/jvm/internal/SuspendLambda.<init> (ILkotlin/coroutines/Continuation;)V
RETURN
MAXSTACK = 3
MAXLOCALS = 3
// access flags 0x0
I label
// access flags 0x1010
final synthetic Lcom/example/dugup/gbd/ExampleUnitTest; this$0
public final create(Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Lkotlin/coroutines/Continuation;
L0
ALOAD 2
LDC "completion"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
NEW com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1
DUP
ALOAD 0
GETFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.this$0 : Lcom/example/dugup/gbd/ExampleUnitTest;
ALOAD 2
INVOKESPECIAL com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.<init> (Lcom/example/dugup/gbd/ExampleUnitTest;Lkotlin/coroutines/Continuation;)V
ASTORE 3
ALOAD 1
CHECKCAST kotlinx/coroutines/CoroutineScope
ALOAD 3
ALOAD 1
CHECKCAST kotlinx/coroutines/CoroutineScope
PUTFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.p$ : Lkotlinx/coroutines/CoroutineScope;
ALOAD 3
ARETURN
L1
LOCALVARIABLE this Lkotlin/coroutines/jvm/internal/BaseContinuationImpl; L0 L1 0
LOCALVARIABLE value Ljava/lang/Object; L0 L1 1
LOCALVARIABLE completion Lkotlin/coroutines/Continuation; L0 L1 2
MAXSTACK = 4
MAXLOCALS = 4
// access flags 0x11
public final invoke(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
ALOAD 0
ALOAD 1
ALOAD 2
CHECKCAST kotlin/coroutines/Continuation
INVOKEVIRTUAL com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.create (Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Lkotlin/coroutines/Continuation;
CHECKCAST com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1
GETSTATIC kotlin/Unit.INSTANCE : Lkotlin/Unit;
INVOKEVIRTUAL com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.invokeSuspend (Ljava/lang/Object;)Ljava/lang/Object;
ARETURN
MAXSTACK = 3
MAXLOCALS = 3
}
com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1是个继承SuspendLambda且实现了Function2的类
SuspendLambda
@SinceKotlin("1.3")
// Suspension lambdas inherit from this class
internal abstract class SuspendLambda(
public override val arity: Int,
completion: Continuation<Any?>?
) : ContinuationImpl(completion), FunctionBase<Any?>, SuspendFunction {
constructor(arity: Int) : this(arity, null)
public override fun toString(): String =
if (completion == null)
Reflection.renderLambdaToString(this) // this is lambda
else
super.toString() // this is continuation
}
Function2
/** A function that takes 2 arguments. */
public interface Function2<in P1, in P2, out R> : Function<R> {
/** Invokes the function with the specified arguments. */
public operator fun invoke(p1: P1, p2: P2): R
}
所以现在真相出来了,(suspend R.() -> T)最终生成了一个个继承SuspendLambda且实现了Function2的类
2,BaseContinuationImpl.create( value: Any?, completion: Continuation<*>): Continuation<Unit>创建的是个啥?
因为它的实现是:
public open fun create(value: Any?, completion: Continuation<*>): Continuation<Unit> {
throw UnsupportedOperationException("create(Any?;Continuation) has not been overridden")
}
这一部分的字节码可以从 com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1找到:
public final create(Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Lkotlin/coroutines/Continuation;
L0
NEW com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1
DUP
ALOAD 0
GETFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.this$0 : Lcom/example/dugup/gbd/ExampleUnitTest;
ALOAD 2
INVOKESPECIAL com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.<init> (Lcom/example/dugup/gbd/ExampleUnitTest;Lkotlin/coroutines/Continuation;)V
ASTORE 3
ALOAD 1
CHECKCAST kotlinx/coroutines/CoroutineScope
ALOAD 3
ALOAD 1
CHECKCAST kotlinx/coroutines/CoroutineScope
PUTFIELD com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.p$ : Lkotlinx/coroutines/CoroutineScope;
ALOAD 3
ARETURN
L1
LOCALVARIABLE this Lkotlin/coroutines/jvm/internal/BaseContinuationImpl; L0 L1 0
LOCALVARIABLE value Ljava/lang/Object; L0 L1 1
LOCALVARIABLE completion Lkotlin/coroutines/Continuation; L0 L1 2
MAXSTACK = 4
MAXLOCALS = 4
我们看看它做了什么:
a,new了一个com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1对象
b,将传入的Object类型参数value强转成CoroutineScope并赋值给com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1.p$
c,返回com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1
所以答案也出来了BaseContinuationImpl.create( value: Any?, completion: Continuation<*>): Continuation<Unit>创建的是com/example/dugup/gbd/ExampleUnitTest$测试协程启动$1
3,Continuation.resumeWith(result: Result<T>)的具体实现是啥?因为你找到的是个接口方法。
/**
* Resumes the execution of the corresponding coroutine passing a successful or failed [result] as the
* return value of the last suspension point.
*/
public fun resumeWith(result: Result<T>)
它的具体实现可以在BaseContinuationImpl中找到:
public final override fun resumeWith(result: Result<Any?>) {
// This loop unrolls recursion in current.resumeWith(param) to make saner and shorter stack traces on resume
var current = this
var param = result
while (true) {
// Invoke "resume" debug probe on every resumed continuation, so that a debugging library infrastructure
// can precisely track what part of suspended callstack was already resumed
probeCoroutineResumed(current)
with(current) {
val completion = completion!! // fail fast when trying to resume continuation without completion
val outcome: Result<Any?> =
try {
val outcome = invokeSuspend(param)
if (outcome === COROUTINE_SUSPENDED) return
Result.success(outcome)
} catch (exception: Throwable) {
Result.failure(exception)
}
releaseIntercepted() // this state machine instance is terminating
if (completion is BaseContinuationImpl) {
// unrolling recursion via loop
current = completion
param = outcome
} else {
// top-level completion reached -- invoke and return
completion.resumeWith(outcome)
return
}
}
}
}
到这里协程启动的流程就看完了。
下面研究一下这个方法:
suspend fun 挂起方法(参数: String): String {
delay(1000)
return 参数
}
这是一个挂起函数,挂起是个什么意思?可以理解为“在没有阻塞线程的情况下延迟协程一段时间,并在指定时间后恢复“。不阻塞的挂起,是个什么意思?o((⊙﹏⊙))o
看看kotlin为我们提供的一个官方的很明显的会有挂起操作的delay方法。
public suspend fun delay(timeMillis: Long) {
if (timeMillis <= 0) return // don't delay
return suspendCancellableCoroutine sc@ { cont: CancellableContinuation<Unit> ->
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)
}
}
cont.context.delay.scheduleResumeAfterDelay(timeMillis, cont)可以简单类比为Handler.postDelayed,也就是延迟多久执行某操作,scheduleResumeAfterDelay是延迟执行cont.resume方法。
suspendCancellableCoroutine方法,通过搜索我们还可以找到一个suspendCoroutine,区别是前一个可以取消。
public suspend inline fun <T> suspendCancellableCoroutine(
crossinline block: (CancellableContinuation<T>) -> Unit
): T =
suspendCoroutineUninterceptedOrReturn { uCont ->
val cancellable = CancellableContinuationImpl(uCont.intercepted(), resumeMode = MODE_CANCELLABLE)
// NOTE: Before version 1.1.0 the following invocation was inlined here, so invocation of this
// method indicates that the code was compiled by kotlinx.coroutines < 1.1.0
// cancellable.initCancellability()
block(cancellable)
cancellable.getResult()
}
这里最明显的方法就是suspendCoroutineUninterceptedOrReturn,来看看的它的实现:
@SinceKotlin("1.3")
@InlineOnly
@Suppress("UNUSED_PARAMETER", "RedundantSuspendModifier")
public suspend inline fun <T> suspendCoroutineUninterceptedOrReturn(crossinline block: (Continuation<T>) -> Any?): T =
throw NotImplementedError("Implementation of suspendCoroutineUninterceptedOrReturn is intrinsic")
o(* ̄︶ ̄*)o没有没实现,不要紧不要紧,因为它有一大段注释,它的主要功能就是获取挂起函数中的当前延续实例,就是帮忙拿到Continuation实例。然后它还有一个Any?类型的返回值,如果返回的是COROUTINE_SUSPENDED这表示挂起函数暂停了执行并且不会返回任何结果,这种情况下,当结果可用于恢复计算时,通过在某个时刻调用Continuation.resumeWith来恢复执行。否则,返回值必须具有可赋值给[T]的类型,并表示此挂起函数的结果, 由于结果类型被声明为Any?,并且无法正确地进行类型检查,但是其正确的返回类型仍然在暂停函数的签名上。上面的话简单点说就是挂起函数可以挂起也可以不挂起,返回COROUTINE_SUSPENDED就是表示挂起了,返回T类型的值就可以直接带着结果走。那么返回值如果获取的呢?
internal fun getResult(): Any? {
installParentCancellationHandler()
if (trySuspend()) return COROUTINE_SUSPENDED
val state = this.state
if (state is CompletedExceptionally) throw recoverStackTrace(state.cause, this)
...//省略了可取消的逻辑
return getSuccessfulResult(state)
}
上面代码中:
a,return COROUTINE_SUSPENDED ,挂起逻辑,表示目标协程还没有执行完,需要等待执行结果
b,throw recoverStackTrace(state.cause, this),拿到异常结果
c,return getSuccessfulResult(state),拿到正常结果
再看看COROUTINE_SUSPENDED是个啥?
@SinceKotlin("1.3")
public val COROUTINE_SUSPENDED: Any get() = CoroutineSingletons.COROUTINE_SUSPENDED
@SinceKotlin("1.3")
@PublishedApi
internal enum class CoroutineSingletons { COROUTINE_SUSPENDED, UNDECIDED, RESUMED }
下面再看看一下代码:
companion object {
@JvmStatic
suspend fun suspendFuncDelay() =
kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<String> {
println("${Thread.currentThread().name}:1")
thread {
Thread.sleep(1000)
println("${Thread.currentThread().name}:2")
it.resume("${Thread.currentThread().name}:4")
}
println("${Thread.currentThread().name}:3")
kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED
}
@JvmStatic
suspend fun suspendFuncImmediately() =
kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn<String> {
println("${Thread.currentThread().name}:1")
"${Thread.currentThread().name}:immediately."
}
}
上面有2个挂起函数,第一个会挂起,第二个直接返回的。
@Test
fun ceshi() = runBlocking {
println(1)
println(suspendFuncDelay())
println(2)
delay(1000)
println(3)
println(suspendFuncImmediately())
println(4)
}
运行一下结果:
1
main @coroutine#1:1
main @coroutine#1:3
Thread-0:2
Thread-0:4
2
3
main @coroutine#1:1
main @coroutine#1:immediately.
4
下面用Java仿写这段逻辑:
public class ContinuationImpl implements Continuation<Object> {
private int lable = 0;
private final Continuation<Unit> completion;
public ContinuationImpl(Continuation<Unit> completion) {
this.completion = completion;
}
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NotNull Object o) {
try {
Object result = o;
switch (lable) {
case 0: {
System.out.println(1);
result = ExampleUnitTest.suspendFuncDelay(this);
lable++;
if (isSuspended(result)) return;
}
case 1:{
System.out.println(result);
System.out.println(2);
result = DelayKt.delay(1000,this);
lable++;
if (isSuspended(result)) return;
}
case 2:{
System.out.println(3);
result = ExampleUnitTest.suspendFuncImmediately(this);
lable++;
if (isSuspended(result)) return;
}
case 3:{
System.out.println(result);
System.out.println(4);
}
}
completion.resumeWith(Unit.INSTANCE);
} catch (Exception e) {
completion.resumeWith(e);
}
}
private boolean isSuspended(Object result) {
return result == IntrinsicsKt.getCOROUTINE_SUSPENDED();
}
}
ContinuationImpl这个类在kotlin的协程标准库里面找到,上面提到的SuspendLambda就是继承与ContinuationImpl,标准库中的resumeWith最终调用到的是invokeSuspend,invokeSuspend就是我们的协程体。
有了这个类我们还需要准备一个 completion 用来接收结果:
public class RunSuspend implements Continuation<Unit> {
private Object result;
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NotNull Object o) {
synchronized (this) {
this.result = o;
notifyAll();
}
}
public void await() throws Throwable {
synchronized (this) {
while (true) {
Object result = this.result;
if (result == null) {
wait();
} else if (result instanceof Throwable) {
throw (Throwable) result;
} else {
return;
}
}
}
}
}
最终运行:
@Test
fun ceshiJava(){
val runSuspend = RunSuspend()
val table = ContinuationImpl(runSuspend)
table.resumeWith(Unit)
runSuspend.await()
}
结果:
1
main:1
main:3
Thread-0:2
Thread-0:4
2
3
kotlinx.coroutines.DefaultExecutor:1
kotlinx.coroutines.DefaultExecutor:immediately.
4
运行结果和上面是一样的。
到这里应该对协程的本质有了一定的了解:
协程的挂起函数本质上就是一个回调,回调类型就是 Continuation
协程体的执行就是一个状态机,每一次遇到挂起函数,都是一次状态转移,就像我们前面例子中的 label 不断的自增来实现状态流转一样
附录:
@Nullable
public final Object suspendFuncImmediately(@NotNull Continuation $completion) {
int var3 = false;
StringBuilder var10000 = new StringBuilder();
Thread var10001 = Thread.currentThread();
Intrinsics.checkExpressionValueIsNotNull(var10001, "Thread.currentThread()");
String var4 = var10000.append(var10001.getName()).append(":1").toString();
boolean var5 = false;
System.out.println(var4);
var10000 = new StringBuilder();
var10001 = Thread.currentThread();
Intrinsics.checkExpressionValueIsNotNull(var10001, "Thread.currentThread()");
String var6 = var10000.append(var10001.getName()).append(":immediately.").toString();
if (var6 == IntrinsicsKt.getCOROUTINE_SUSPENDED()) {
DebugProbesKt.probeCoroutineSuspended($completion);
}
return var6;
}
这个是把上面suspendFuncImmediately函数反编译成Java之后的代码,可以看到suspendFuncImmediately的参数多了一个Continuation,返回值变成了Obeject。
启动协程的3个参数都已经讲完了
CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job
那么下一张将CoroutineScope。