Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# other
.idea
target

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.example.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

public class CompletableFutureExamples2 {
public static void main(String[] args) {

System.out.println("Beginning of the program");

CompletableFuture.supplyAsync(new Supplier<Integer>() {

@Override
public Integer get() {
return longNetworkProcess(5);
}
}).thenAccept(value -> System.out.println(value));

sleep(5);
System.out.println("End of the program");
}

public static int longNetworkProcess(int value) {
sleep(3);

return value * 10;
}

public static void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ public static void main(String[] args) {
long start = System.currentTimeMillis();

cars().thenCompose(cars -> {

// set the rating of each car
List<CompletionStage<Car>> updatedCars = cars.stream()
.map(car -> rating(car.manufacturerId).thenApply(r -> {
car.setRating(r);
Expand All @@ -20,8 +22,10 @@ public static void main(String[] args) {

CompletableFuture<Void> done = CompletableFuture
.allOf(updatedCars.toArray(new CompletableFuture[updatedCars.size()]));

return done.thenApply(v -> updatedCars.stream().map(CompletionStage::toCompletableFuture)
.map(CompletableFuture::join).collect(Collectors.toList()));

}).whenComplete((cars, th) -> {
if (th == null) {
cars.forEach(System.out::println);
Expand All @@ -43,6 +47,7 @@ static CompletionStage<Float> rating(int manufacturer) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}

switch (manufacturer) {
case 2:
return 4f;
Expand All @@ -61,6 +66,7 @@ static CompletionStage<List<Car>> cars() {
carList.add(new Car(1, 3, "Fiesta", 2017));
carList.add(new Car(2, 7, "Camry", 2014));
carList.add(new Car(3, 2, "M2", 2008));

return CompletableFuture.supplyAsync(() -> carList);
}

Expand Down
Loading