Lab 08 - Exercise 7, Asynchronous Programming
Exercise 7 Review
For this part, the implementation of each method can be found in Exercise 7 — Infinite List.
head() — Retrieve the Head Safely
Write the naive if-else statement first, then convert it into a one-line.
tail() — Retrieve the Tail
We want the tail, but we use the head to do the if-else, so a mapping is needed.
map() — How to map the List Efficiently
Use the succinct way, your this.head and this.tail are already Lazy, can just call the method.
forEach()
Traverse through the list by shrinking the tail. This is awesome!
public void forEach(Consumer<? super T> action) {
InfiniteList<T> currList = this;
while (!currList.isSentinel()) {
// Consume the head
currList.head.get().ifPresent(action); // Maybe<T>::ifPresent
// Shrink the sublist
currList = currList.tail.get();
}
}public void forEach(Consumer<? super T> action) {
this.head.get().ifPresent(action);
this.tail.get().forEach(action);
}reduce()
Traverse through the list
If the head exists, do the function you want
If your head exists, total = partial + h + total in tail
Otherwise, total = partial + total in tail
Asynchronous Programming
CompletableFuture<T>
CompletableFuture<T>It can be interpreted as a task which will return a result of type T when completed.
Common Completable Future methods
CF(f).then(g)means: startgonly afterfhas been completed.Examples:
thenRun,thenCombine,thenApply
static CF.async(g)means: startgon a new threadExamples:
supplyAsync,runAsync
CF(f).then...async(g)means: startgonly afterfhas been completed, but use a new thread.Examples:
thenRunAsync,thenApplyAsync.
Difference between run and supply: run executes a void
function while supply executes a function with a return
value.
Last updated