kotlinkotlin-coroutines

Will kotlin method 'runMain' lead memory leak?


In kotlin sources,we can see method ‘runMain’ like this:

fun runMain(block: () -> Unit) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        block()
    } else {
        Handler(Looper.getMainLooper()).post { block() }
    }
}

Wouldn't frequent creation of handlers cause memory leaks?

If in a child thread, call the runMain method quickly and frequently


Solution

  • No, because Handler objects will be collected by the Garbage Collector since they're not referenced.