2. Long running task
● Dependent Tasks
Retrieving data from server
Processing data
Writing to storage
Showing result to user
3. Blocking API
executor.execute(() -> {
UserDto dto = service.retrieveUser();
User user = accounts.processUser(dto);
Storage.writeUser(user);
});
● Coarse-grained
– Web service, DB, Process Data
● Control flow is verbose
– if-else, try-catch-finally
11. Scala
val f1 = future{ service.retrieveUserInfo() }
val f2 = f1.map{ dto =>
accounts.processDto(dto)
}
val f3 = f2.map{ user=>
storage.writeUser(user)
}
f3 onComplete{
case Success(_) => …
case Failure(t) => println()
}
12. What is Future?
● Future, promise, and delay
– They describe an acts as a proxy for a result that is
initially unknown, usually because the computation
of its value is yet incomplete
– They are often used Interchangeably
● Some differences in usage
between future and promise
– Future read
– Promise write
24. Write methods
● When two or more threads attempt to
complete, completeExceptionally, or
cancel a CompletableFuture, only one
of them succeeds
/*
* @param mayInterruptIfRunning this value has no effect in
* this implementation because interrupts are not used to
* control processing.
**/
public boolean cancel(boolean
mayInterruptIfRunning)
29. whenComplete
CompletableFuture<T> whenComplete(
BiConsumer<? super T,? super Throwable>
action)
future = doSomeThing();
/** returns a new CompletionStage with
* the same result or exception as this stage
*/
future2 =
future.whenComplete((result, throwable -> {
//... do something with result
});
39. API variation
● Without Async postfix
– By the thread complete current future or any
other caller of a completion method
● With Async postfix
– Using ForkJoinPool.commonPool()
● With Async postfix and Executor
param
– Using Executor
45. 參考資料
● Java Concurrency in Practice
● The way of the Future, Futures in .NET, Java
and JavaScript
– http://blog.softmemes.com/2012/06/18/the-way-of-the-fu
● [concurrency-interest] Interface
CompletionStage
– http://cs.oswego.edu/pipermail/concurrency-interest/201
46. 參考資料
● SIP-14 - Futures and Promises
– http://docs.scala-lang.org/sips/pending/futures-promises
● Java 8: Definitive guide to CompletableFuture
– http://nurkiewicz.blogspot.no/2013/05/java-8-definitive-g
● Java 8: CompletableFuture in action
– http://nurkiewicz.blogspot.no/2013/05/java-8-completabl
● Futures and Promises in Scala 2.10
– https://speakerdeck.com/heathermiller/futures-and-prom