Coroutine Self-Waiting


Hi,recently i started working with coroutines.
By mistake made some deadlock when coroutine waits for himself.
It was not trivial, cause action was hidden in sub-function.

Maybe we can track this trivial case, and make some warring in this case?

var job : Deferred<Unit?>? = null
fun main(args:Array<String>) {

    job = async { close_all() }

    runBlocking {

fun close_all(){
    println("Closing all Operations")
    runBlocking {


TL;DR. Not really possible.

What you are talking about takes some seriously complex control flow analysis and that is just the case when your job variable is a val. The compiler would need to check all possible paths through your program. Also you are talking about coroutines so there is parallel execution and stuff. The point is, even if it is possible in some rare cases to detect such an error statically it would be very complex to implement and be very error prone. It would never find all cases so the feature would not be reliable and it would take a long time.


Well, i suppose you cannot do this by IDE. But you can still detect it during execution. As i understand you can just check if inside the job you are waiting for yourself, then just give a warring message (Of course there should be way to cancel this message in some weird cases).


I consider your suggestion as a very hard task, however you can write an extension method awaitForAnotherJob to achieve this goal.

Finally you have not to use async in this way to invoke the blocking funcion close_all(), async should contain a suspending lambda