11. Week 10: Asynchronous Computations and Futures
Useful resources:
Code with examples, package
futures
11.1. Summary of the Lecture
A short summary of the files from the accompanying code is given below, outlining the characteristic aspects of working with Java Futures, as well as Scala Futures and Promises. It is recommended that the files are explored in the order they appear in the following list:
Java Futures
SortAndRead
— reading a user input after having performed a costly operation (array sorting). This examples demonstrates the need for parallelisation.SortAndRead2
— a better version of the previous program. Sorting is moved into a separate future. Introducing Java’s thread pools and the classFuture
.SortAndRead3
— even better implementation, in which the user input is also moved into a separate future.
An Exercise on Java Futures
FutureSort
— an old friend, parallel quick-sort, now re-implemented with Java futures. An interesting question is why some of the offered thread pools, e.g.,Executors.newFixedThreadPool(4)
make it deadlock?
Scala Futures
FutureDataType
— a first example of using Scala’s futures, itsisCompleted
method and the implicit execution context (ExecutionContext.Implicits.global
).FuturesCallbacks
— demonstration of processing results of the futures asynchronously via callbacks (usingforeach
method).FutureExceptions
— treatment of exceptions in futures, viaonComplete
method and pattern matching on the result class:Success
orFailure
.AwaitExample
— an example showing the use ofAwait.result
method to wait for a future to complete or fail otherwise.
Composing Scala Futures
Options
— a quick practice on building combinators for theOption
type. Serves as an introduction to similar future combinators introduced next.ComposingFutures
— an example of composing two futures running asynchronously, via the explicitflatMap
combinator (or using thefor
notation). Check: what changes in the execution if the futures are inlined under thefor
comprehension?BlacklistedFiles
— a large example involving composing futures in the implementation ofgetAllBlacklisted
. Multiple ways to query the result are possible.ScalaFuturesTests
— shows how to test futures.
Scala Promises
ProducerConsumer
— implementation of a producer-consumer with a promise, which serves as a single-assignment mailbox.ProducerConsumer2
— demonstration ofisCompleted
method of promises.ProducerConsumer3
— failing the promise and recovering after an exception in the future using therecover
method.