Skip to content

Instantly share code, notes, and snippets.

@elizarov
Last active November 14, 2016 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elizarov/68093e8ef8bebbd87e1f4a51190bb629 to your computer and use it in GitHub Desktop.
Save elizarov/68093e8ef8bebbd87e1f4a51190bb629 to your computer and use it in GitHub Desktop.
Demo the problem with naive await implementation
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