Android使用coroutine发生栈溢出。

我在读一个特别大的文件,其中的while循环次数比较多。

由于是超时操作,我使用了coroutine来执行这个操作。

起初我以为是while循环的问题,但是while循环不会有一直压栈不弹出的情况。

看到错误日志下面关于coroutine的堆栈,我采用了Thread来执行这段函数,发现并不报错了,定位到时因为coroutine的resumeWith导致的。

因为coroutine在执行suspend函数的时候是分段实行的,根据内部状态机不停的回调resumewith函数。

11-19 11:19:14.451 28024 28352 E AndroidRuntime: Process: com.macoli.mockserver, PID: 28024
11-19 11:19:14.451 28024 28352 E AndroidRuntime: java.lang.StackOverflowError: stack size 1040KB
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at java.lang.String.indexOf(String.java:1711)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlin.text.StringsKt__StringsKt.indexOf(Strings.kt:1105)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlin.text.StringsKt__StringsKt.indexOf$default(Strings.kt:1101)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlin.text.StringsKt__StringsKt.contains(Strings.kt:1146)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlin.text.StringsKt__StringsKt.contains$default(Strings.kt:1144)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at com.macoli.mockserver.car.CarHandler.parseLog(CarHandler.kt:125)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at com.macoli.mockserver.car.CarHandler$startWebServer$1.invokeSuspend(CarHandler.kt:46)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
11-19 11:19:14.451 28024 28352 E AndroidRuntime:        at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)

解决办法:提升coroutine版本

implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")

参考:

https://github.com/Kotlin/kotlinx.coroutines/issues/2541

猜你喜欢

转载自blog.csdn.net/mldxs/article/details/127934720