Last active
November 14, 2016 18:19
-
-
Save elizarov/68093e8ef8bebbd87e1f4a51190bb629 to your computer and use it in GitHub Desktop.
Demo the problem with naive await implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.CompletableFuture | |
// ====================================================================================================== | |
// demo the problem with naive await implementation | |
fun main(args: Array<String>) { | |
val n: Int = 100000 | |
var actualCount = 0; | |
async<Unit> { | |
repeat(n) { // repeat n times | |
actualCount++ | |
await(someAsyncOperation()) | |
} | |
} | |
print("Actually executed $actualCount times, expected $n times") | |
} | |
fun someAsyncOperation(): CompletableFuture<Unit> { | |
// return a future that is already completed | |
return CompletableFuture.completedFuture(Unit) | |
} | |
// ====================================================================================================== | |
// code copied from https://github.com/Kotlin/kotlin-coroutines/blob/master/examples/async.kt | |
fun <T> async(coroutine c: FutureController<T>.() -> Continuation<Unit>): CompletableFuture<T> { | |
val controller = FutureController<T>() | |
controller.c().resume(Unit) | |
return controller.future | |
} | |
class FutureController<T> { | |
val future = CompletableFuture<T>() | |
suspend fun <V> await(f: CompletableFuture<V>, machine: Continuation<V>) { | |
f.whenComplete { value, throwable -> | |
if (throwable == null) | |
machine.resume(value) | |
else | |
machine.resumeWithException(throwable) | |
} | |
} | |
operator fun handleResult(value: T, c: Continuation<Nothing>) { | |
future.complete(value) | |
} | |
operator fun handleException(t: Throwable, c: Continuation<Nothing>) { | |
future.completeExceptionally(t) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment