Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Coroutines vs CompletableFuture

Can anybody explain me why people should use coroutines? Is there some coroutine code example which shows better completion time against regular java concurrent code (without magical delay() function, nobody uses delay() in production) ?

In my personal example coroutines(line 1) are suck against java code(line 2). Maybe i did something wrong?

Example:

import kotlinx.coroutines.*
import java.time.Instant
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future

@ExperimentalCoroutinesApi
fun main() = runBlocking {
    val begin = Instant.now().toEpochMilli()
    val jobs = List(150_000) {
        GlobalScope.launch { print(getText().await()) } // :1
//        CompletableFuture.supplyAsync { "." }.thenAccept { print(it) } // :2
    }
    jobs.forEach { it.join() }
    println(Instant.now().toEpochMilli() - begin)
}

fun getText(): Future<String> {
    return CompletableFuture.supplyAsync {
        "."
    }
}

@ExperimentalCoroutinesApi
suspend fun <T> Future<T>.await(): T = suspendCancellableCoroutine { cont ->
    cont.resume(this.get()) {
        this.cancel(true)
    }
}

Additional question:

Why i should create this coroutine wrapper await()? It seems does not improve coroutine version of code otherwise get() method complains on inappropriate blocking method call?

like image 499
lalilulelo_1986 Avatar asked Dec 07 '22 11:12

lalilulelo_1986


1 Answers

The goal of coroutines is not "better completion time." The goal -- at which it succeeds quite well, honestly -- is that coroutines are easier to use.

That said, what you've done in your code is not at all a good way to compare the speed of two alternate approaches. Comparing the speed of things in Java and getting realistic results is extremely hard, and you should read How do I write a correct micro-benchmark in Java? at a minimum before attempting it. The way you are currently attempting to compare two pieces of Java code will lie to you about the realistic performance behavior of your code.

To answer your additional question, the answer is that you should not create that await method. You should not use get() -- or java.util.concurrent.Future -- with coroutine code, whether it's in suspendCancellableCoroutine or otherwise. If you want to use a CompletableFuture, use the provided library to interact with it from coroutine code.

like image 94
Louis Wasserman Avatar answered Dec 11 '22 10:12

Louis Wasserman