Created
October 22, 2021 20:07
-
-
Save alexey-ulashchick/dfcc50c9ff627cdc5d135508ff56a4e9 to your computer and use it in GitHub Desktop.
CompletableFuture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Comparator; | |
| import java.util.List; | |
| import java.util.Set; | |
| import java.util.concurrent.*; | |
| import java.util.stream.Collectors; | |
| import java.util.stream.LongStream; | |
| class Scratch { | |
| public static final Set<Long> SHOP_IDS = LongStream.range(0, 10L).boxed().collect(Collectors.toSet()); | |
| public static final long ITEM_ID = 123L; | |
| public static final int MIN_PRICE = 10; | |
| public static final int MAX_PRICE = 20; | |
| public static final int SHOP_RESPONSE_TIME_MAX_S = 5; | |
| public static final int TIMEOUT_MS = 3_000; | |
| public static final double PRICE_NOT_FOUND = -1.0; | |
| public static double getPrice(long itemId, long shopId) { | |
| try { | |
| final int delayMs = ThreadLocalRandom.current().nextInt(SHOP_RESPONSE_TIME_MAX_S) * 1_000; | |
| final int value = ThreadLocalRandom.current().nextInt(MIN_PRICE, MAX_PRICE + 1); | |
| final String message = String.format("Thread[%s]. Delay=%d, Value=%d", | |
| Thread.currentThread().getName(), delayMs, value); | |
| System.out.println(message); | |
| Thread.sleep(delayMs); | |
| return value; | |
| } catch (InterruptedException e) { | |
| return PRICE_NOT_FOUND; | |
| } | |
| } | |
| public static double getMinPrice(long itemId) throws ExecutionException, InterruptedException { | |
| final List<CompletableFuture<Double>> futures = SHOP_IDS.stream() | |
| .map(shopId -> CompletableFuture | |
| .supplyAsync(() -> getPrice(itemId, shopId)) | |
| .exceptionally(ex -> PRICE_NOT_FOUND)) | |
| .collect(Collectors.toList()); | |
| return CompletableFuture | |
| .allOf(futures.toArray(CompletableFuture[]::new)) | |
| .orTimeout(TIMEOUT_MS, TimeUnit.MILLISECONDS) | |
| .handle((unused, ex) -> futures.stream() | |
| .map(future -> future.getNow(PRICE_NOT_FOUND)) | |
| .filter(price -> price != PRICE_NOT_FOUND) | |
| .min((a, b) -> Comparator.<Double>naturalOrder().compare(a, b)) | |
| .orElse(PRICE_NOT_FOUND)) | |
| .get(); | |
| } | |
| public static void main(String[] args) throws InterruptedException, ExecutionException { | |
| System.out.println("Min price = " + getMinPrice(ITEM_ID)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment