The document discusses CompletableFuture in Java and provides the following information:
- CompletableFuture allows composing asynchronous operations in a sequential manner without blocking threads. It implements Future and CompletionStage interfaces.
- The API includes methods for creating CompletableFutures, transforming results, error handling, combining results from multiple CompletableFutures, and retrieving final values.
- Benchmarks show CompletableFuture has lower overhead than using raw Future for simple asynchronous operations, especially when work is split across multiple threads.
3. Safe Harbor Statement
The following is intended to outline our general product direction. It
is intended for information purposes only, and may not be
incorporated into any contract. It is not a commitment to deliver any
material, code, or functionality, and should not be relied upon in
making purchasing decisions. The development, release, and timing
of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 3/45
5. Параллелизм в Java: *Отступление
∙
JDK 7 EOL
∙
JDK 8u
∙
JDK 9 EA
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 5/45
6. Параллелизм в Java: История
∙
Threads
– Monitors
– Locks and other primitives
∙
Executors
– Runnable<T>, Callable<T> → lambdas
∙
Future<T>
∙
ForkJoinPool
∙
stream.parallel()
∙
Explicit → implicit
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 6/45
7. Параллелизм в Java: Future<T>
∙
Обёртка для результата, доступного в будущем
∙
Получение значения требует проверки исключений
– ExecutionException содержит исходное исключение
∙
Исполняется в каком-то потоке и блокирует какой-то
(другой) поток
∙
Можно проверить, доступно ли уже значение
∙
Можно отменить вычисление
Future f = executor.submit (() -> ...);
result = f.get (); // love to be BLOCKED here
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 7/45
13. CompletableFuture: Боремся с вложенностью
CompletableFuture . supplyAsync (() -> readFile(file ))
. thenComposeAsync (content -> processContent (content ))
. whenComplete ((result , ex) -> {
if (ex == null) {
System.out.println(result );
} else {
ex. printStackTrace ();
}
});
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 12/45
14. CompletableFuture: Композиция
∙
Method chaining
– Нет блокирующих вызовов
– Знакомо и удобно (builders, mocks, streams)
∙
Работаем с несколькими CF
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 13/45
16. Что за класс: CompletableFuture<T>
∙
Core library class since Java SE 8
∙
implements Future<T>
∙
implements CompletionStage<T>
– Элемент композиции
– Вычисление функции
– Связь через результаты
– Методы преобразований
– toCompletableFuture()
∙
Асинхронные операции
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 15/45
17. Методы: Создание
∙
CompletableFuture()
– boolean complete(T value), успешно только для одного потока
– boolean completeExceptionally(Throwable ex)
∙
CompletableFuture<U> completedFuture(U value)
∙
CompletableFuture<U>
supplyAsync(Supplier<U> supplier [, Executor executor])
∙
CompletableFuture<Void>
runAsync(Runnable runnable [, Executor executor])
∙
ForkJoinPool.commonPool() по умолчанию
– если выключен, new Thread()
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 16/45
18. Методы: Создание
CompletableFuture <Long > cf1 = CompletableFuture . supplyAsync (() -> 42L);
CompletableFuture <Long > start = CompletableFuture . completedFuture (42L);
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 17/45
19. Методы: *Отступление
Упрощённая запись generics
∙
Function<? super T,? extends U>
→ Function<T,U>
∙
Consumer<? super T> → Consumer<T>
∙
. . .
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 18/45
32. Методы: Исполнение в потоках
∙
isDone() → исполнение метода в текущем потоке
– Если не ...Async()
– И для exceptionally()
∙
helpPostComplete() на любой чих помогаем будить ждущих
– И для exceptionally()
– И для повторных вызовов complete()
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 29/45