SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
CompletableFuture
уже здесь
Дмитрий Чуйко
dmitry.chuyko@oracle.com
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved.
Содержание
Введение
API
Накладные расходы
Пример. Rest-сервис
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 2/45
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
Введение
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/45
Параллелизм в Java: *Отступление
∙
JDK 7 EOL
∙
JDK 8u
∙
JDK 9 EA
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 5/45
Параллелизм в 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
Параллелизм в 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
Сложности: Обработка ошибок
try {
try {
return parse(fileObject , content.get ());
} catch ( ExecutionException e) {
unfold(e);
}
} catch ( IOException e) {
log.error(e, fileObject );
} catch ( InterruptedException e) {
throw new RuntimeException (e);
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/45
Сложности: Обработка ошибок
private static void unfold( ExecutionException e) throws IOException ,
InterruptedException {
Throwable cause = e.getCause ();
if (cause instanceof ExecutionException )
unfold (( ExecutionException ) cause );
if (cause instanceof IOException )
throw ( IOException) cause;
if (cause instanceof InterruptedException )
throw ( InterruptedException ) cause;
if (cause instanceof Error)
throw (Error) cause;
if (cause instanceof RuntimeException )
throw ( RuntimeException ) cause;
throw new RuntimeException (e);
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 9/45
Сложности: Давайте добавим обработчики!
readFileAsync (file ,
content -> System.out.println(content),
ex -> ex. printStackTrace ();
);
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/45
Сложности: Давайте добавим обработчики!
readFileAsync (file ,
content -> System.out.println(content),
ex -> ex. printStackTrace ();
);
∙
↓Добро пожаловать сюда↓
http://callbackhell.com/
readFileAsync (file ,
content -> processContentAsync (content ,
c -> System.out.println(c),
e -> e. printStackTrace ()
);
ex -> ex. printStackTrace ();
);
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/45
Сложности: Результат
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 11/45
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
CompletableFuture: Композиция
∙
Method chaining
– Нет блокирующих вызовов
– Знакомо и удобно (builders, mocks, streams)
∙
Работаем с несколькими CF
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 13/45
API
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 14/45
Что за класс: 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
Методы: Создание
∙
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
Методы: Создание
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
Методы: *Отступление
Упрощённая запись 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
Методы: Трансформации
∙
CompletableFuture<U> thenApply(Function<T,U> fn)
– Нет "Async"→ продолжаем в том же потоке
∙
CompletableFuture<U>
thenApplyAsync(Function<T,U> fn [, Executor executor])
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 19/45
Методы: Трансформации (map)
CompletableFuture <Long > cf2 = CompletableFuture
.supplyAsync (() -> 42L)
.thenApply(r1 -> r1 + 2015);
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 20/45
Методы: Подписка
∙
CompletableFuture<Void> thenAccept(Consumer<T> block);
∙
CompletableFuture<Void> thenRun(Runnable action);
∙
Async versions
CompletableFuture <Void > cf3 = CompletableFuture
.supplyAsync (() -> 42L)
.thenApply(r1 -> r1 + 2015)
.thenAccept(System.out:: println );
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 21/45
Методы: Обработка ошибок
∙
CompletableFuture<T>
exceptionally(Function<Throwable, T> fn)
∙
CompletableFuture<U>
handle(BiFunction<T, Throwable, U> fn)
∙
Ошибка пробрасывается по цепочкам
CompletableFuture . supplyAsync (() -> readFile(file ))
. thenComposeAsync (content -> processContent (content ))
.thenAccept(System.out:: println)
. exceptionally (Throwable :: printStackTrace );
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 22/45
Методы: Обработка ошибок
CompletableFuture <Void > cf = new CompletableFuture < >();
cf. completeExceptionally (new RuntimeException ());
//cf. completeExceptionally (new CompletionException (new RuntimeException ()));
cf. exceptionally (e -> {
System.out.println(e);
return null;
});
cf.thenApply(Function.identity ()). exceptionally (e -> {
System.out.println(e); // CompletionException : RuntimeException - not this stage
return null;
});
cf.get (); // ExecutionException : RuntimeException
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 23/45
Методы: Комбинация (reduce)
∙
CompletableFuture<V>
thenCombine (CompletionStage<U> other,
BiFunction<T,U,V> fn)
CompletableFuture <Long > cf2 = CompletableFuture
.supplyAsync (() -> 42L)
.thenCombine ( CompletableFuture . supplyAsync (() -> 2015) , Math ::min);
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 24/45
Методы: Для набора
∙
CompletableFuture<Object>
anyOf(CompletableFuture<?>... cfs)
∙
CompletableFuture<Void>
allOf(CompletableFuture<?>... cfs)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 25/45
Методы: Композиция (flatMap)
∙
CompletableFuture<U>
thenCompose(Function<T,CompletableFuture<U>> fn)
CompletableFuture <Long > cff = CompletableFuture
.supplyAsync (() -> 42L)
.thenCompose (x -> CompletableFuture .supplyAsync (() -> x + 2015));
CompletableFuture <CompletableFuture <Long >> cff = CompletableFuture
.supplyAsync (() -> 42L)
.thenApply(x -> CompletableFuture . supplyAsync (() -> x + 2015));
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 26/45
Методы: Get
∙
T get() throws InterruptedException, ExecutionException
∙
T get(long timeout, TimeUnit unit) throws
InterruptedException, ExecutionException, TimeoutException
∙
T getNow(T valueIfAbsent)
∙
T join()
– Нет checked exceptions (CompletionException)
...
stream.map(x -> CompletableFuture ...). map( CompletableFuture :: join)
...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 27/45
Методы: Get
// parallel where?
stream.parallel ()
.map(x -> CompletableFuture .supplyAsync ...)
.map( CompletableFuture :: join );
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/45
Методы: Get
// parallel where?
stream.parallel ()
.map(x -> CompletableFuture .supplyAsync ...)
.map( CompletableFuture :: join );
// NOT Executors. newSingleThreadExecutor ();
ExecutorService es1 = new ForkJoinPool (1);
Future <?> task1 = es1.submit (() -> {
try {
es1.submit (()-> System.out.println("1")). get ();
} catch (Exception e) {
}
});
task1.get ();
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/45
Методы: Get
// parallel where?
stream.parallel ()
.map(x -> CompletableFuture .supplyAsync ...)
.map( CompletableFuture :: join );
// NOT Executors. newSingleThreadExecutor ();
ExecutorService es1 = new ForkJoinPool (1);
Future <?> task1 = es1.submit (() -> {
try {
es1.submit (()-> System.out.println("1")). get ();
} catch (Exception e) {
}
});
task1.get ();
// parallel where?
CompletableFuture . supplyAsync (() -> stream (). parallel ()... , fjpN );
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/45
Методы: Исполнение в потоках
∙
isDone() → исполнение метода в текущем потоке
– Если не ...Async()
– И для exceptionally()
∙
helpPostComplete() на любой чих помогаем будить ждущих
– И для exceptionally()
– И для повторных вызовов complete()
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 29/45
Накладные расходы
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 30/45
Бенчмарк: Окружение
∙
Intel Core i5-3320M (1x2x2, 3.3 GHz)
∙
Linux x64 (kernel 3.19)
∙
JDK 9 EA (b64)
∙
OpenJDK JMH 1.10-SNAPSHOT
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 31/45
Бенчмарк: Базовые операции
@Param ({ "1024" })
public volatile int loada;
@Param ({ "1024" })
public volatile int loadb;
Integer a() {
Blackhole.consumeCPU(loada );
return loada;
}
Integer b() {
Blackhole.consumeCPU(loadb );
return loadb;
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 32/45
Бенчмарк: Что сравниваем
Простой вариант
@Benchmark
public Integer ab() {
return a() * b();
}
@Benchmark
public Integer stream () throws InterruptedException , ExecutionException {
return IntStream.range (0, 2)
.mapToObj ((i) -> i == 0 ? a() : b())
.reduce (1, (a, b) -> a * b);
}
@Benchmark
public Integer parstream () throws InterruptedException , ExecutionException {
return IntStream.range (0, 2). parallel ()
.mapToObj ((i) -> i == 0 ? a() : b())
.reduce (1, (a, b) -> a * b);
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 33/45
Бенчмарк: Что сравниваем
Future
@Benchmark
public Integer future2 () throws InterruptedException , ExecutionException {
ExecutorService fjp = ForkJoinPool .commonPool ();
Future <Integer > fa = fjp.submit (() -> a());
Future <Integer > fb = fjp.submit (() -> b());
return fa.get() * fb.get ();
}
@Benchmark
public Integer future3 () throws InterruptedException , ExecutionException {
ExecutorService fjp = ForkJoinPool .commonPool ();
Future <Integer > fa = fjp.submit (() -> a());
Future <Integer > fb = fjp.submit (() -> b());
return fjp.submit (() -> fa.get() * fb.get ()). get ();
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 34/45
Бенчмарк: Что сравниваем
CompletableFuture
@Benchmark
public Integer cf2() throws InterruptedException , ExecutionException {
return CompletableFuture . supplyAsync (() -> a())
.thenCombine ( CompletableFuture . supplyAsync (() -> b()), (a, b) -> a * b)
.get ();
}
@Benchmark
public Integer cf3() throws InterruptedException , ExecutionException {
return CompletableFuture . supplyAsync (() -> a())
. thenCombineAsync ( CompletableFuture .supplyAsync (() -> b()), (a, b) -> a * b)
.get ();
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 35/45
Бенчмарк: Результаты
Параметры по умолчанию (loada=loadb=1K)
Вариант 𝜇c/оп
ab 6 ± 1
cf2 4 ± 1
cf3 4 ± 1
future2 8 ± 1
future3 8 ± 1
parstream 7 ± 1
stream 6 ± 1
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 36/45
Бенчмарк: Результаты
Оценка пустой операции (loada=loadb=0)
Вариант Время, нc/оп Аллокации, B/оп
ab 11 ± 1 0 ± 0
cf2 715 ± 11 200 ± 1
cf3 1060 ± 17 204 ± 2
future2 4733 ± 135 80 ± 1
future3 4657 ± 213 128 ± 1
parstream 421 ± 24 496 ± 1
stream 131 ± 1 248 ± 1
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/45
Бенчмарк: Результаты
Долгая операция (loada=loadb=128K)
Вариант 𝜇c/оп
ab 713 ± 1
cf2 383 ± 8
cf3 393 ± 10
future2 386 ± 8
future3 387 ± 9
parstream 378 ± 10
stream 713 ± 1
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 38/45
Пример. Rest-сервис
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 39/45
Сервис: Ингридиенты
∙
JDK 8u25
∙
JAX-RS 2.0
https://jax-rs-spec.java.net/
∙
Jersey RI
https://jersey.java.net/
∙
Grizzly NIO framework
https://grizzly.java.net/
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 40/45
Сервис: Ингридиенты
∙
JDK 8u25
∙
JAX-RS 2.0
https://jax-rs-spec.java.net/
∙
Jersey RI
https://jersey.java.net/
∙
Grizzly NIO framework
https://grizzly.java.net/
∙
CompletableFuture
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 40/45
Сервис: Запускалка
public class Main {
public static final String BASE_URI = "http :// localhost :8080/ jee/";
public static void main(String [] args) throws IOException {
ResourceConfig rc = new ResourceConfig (). packages("com.oracle.demo");
HttpServer server = GrizzlyHttpServerFactory
. createHttpServer (URI.create(BASE_URI), rc);
System.out.println(String.format("Jersey␣app␣started␣"
+ "with␣WADL␣available␣at␣% sapplication .wadln"
+ "Hit␣enter␣to␣stop␣it...", BASE_URI ));
System.in.read ();
server.shutdownNow ();
}
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 41/45
Сервис: Endpoint
@Path("jeeconf")
public class JEEConf {
@Inject
DataService dataService ;
// @ManagedAsync -- NOT NEEDED
@GET
@Produces(MediaType.TEXT_PLAIN)
public void asyncGet(@Suspended final AsyncResponse asyncResponse ) {
dataService
. findAudience ()
. thenCombine( dataService. findImpression (), (a, b) -> a + b)
.thenApply( asyncResponse :: resume)
. exceptionally ( asyncResponse :: resume );
// way #1
asyncResponse .setTimeout (1, SECONDS );
asyncResponse . setTimeoutHandler (ar -> ar.resume(new TimeoutException ()));
}
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 42/45
Сервис: Provider
Часть 1/2
@ManagedBean
@Path("data")
public class DataService {
// @Inject
ScheduledExecutorService shedPool = Executors. newScheduledThreadPool (1);
public CompletableFuture <String > findAudience () {
return find("audience");
}
public CompletableFuture <String > findImpression () {
return find("impression");
}
@PreDestroy
public void shutdown () {
shedPool.shutdownNow ();
}
...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 43/45
Сервис: Provider
Часть 2/2
public CompletableFuture <String > find(String path) {
CompletableFuture <String > promise = new CompletableFuture < >();
CompletableFuture
.runAsync (() -> {
try {
promise.complete(new String(Files. readAllBytes (Paths.get(path ))));
} catch ( IOException e) {
promise. completeExceptionally (e);
}
});
// way #2. and impact on shedPool.
shedPool.schedule(
() -> promise. completeExceptionally (new TimeoutException ()), 1, SECONDS );
return promise;
}
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 44/45
Сервис: ExceptionMapper
@Provider
public class CompletionExceptionMapper
implements ExceptionMapper <CompletionException > {
public Response toResponse( CompletionException bex) {
return Response.status(Status. BAD_REQUEST)
.entity(new File("error.png")). type("image/png"). build ();
}
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 45/45

Contenu connexe

Tendances

Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]
Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]
Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]David Buck
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?Edward Burns
 
Java 10 New Features
Java 10 New FeaturesJava 10 New Features
Java 10 New FeaturesAli BAKAN
 
55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9Simon Ritter
 
invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]David Buck
 
JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]
JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]
JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]David Buck
 
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...David Buck
 
Production Time Profiling Out of the Box
Production Time Profiling Out of the BoxProduction Time Profiling Out of the Box
Production Time Profiling Out of the BoxMarcus Hirt
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondSimon Ritter
 
Head toward Java 14 and Java 15 #LINE_DM
Head toward Java 14 and Java 15 #LINE_DMHead toward Java 14 and Java 15 #LINE_DM
Head toward Java 14 and Java 15 #LINE_DMYuji Kubota
 
Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Edward Burns
 
JDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerJDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerSimon Ritter
 
JDK 9: Mission Accomplished. What Next For Java?
JDK 9: Mission Accomplished. What Next For Java?JDK 9: Mission Accomplished. What Next For Java?
JDK 9: Mission Accomplished. What Next For Java?Simon Ritter
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveSimon Ritter
 
Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]
Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]
Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]David Buck
 
Head toward Java 14 and Java 15
Head toward Java 14 and Java 15Head toward Java 14 and Java 15
Head toward Java 14 and Java 15Yuji Kubota
 
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...Nikita Lipsky
 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaC4Media
 

Tendances (20)

Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]
Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]
Java Concurrency, A(nother) Peek Under the Hood [Code One 2019]
 
JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?JavaOne 2014 BOF4241 What's Next for JSF?
JavaOne 2014 BOF4241 What's Next for JSF?
 
Java 10 New Features
Java 10 New FeaturesJava 10 New Features
Java 10 New Features
 
55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9
 
invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]invokedynamic for Mere Mortals [Code One 2019]
invokedynamic for Mere Mortals [Code One 2019]
 
JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]
JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]
JDK Mission Control: Where We Are, Where We Are Going [Code One 2019]
 
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
Hangs, Slowdowns, Starvation—Oh My! A Deep Dive into the Life of a Java Threa...
 
Production Time Profiling Out of the Box
Production Time Profiling Out of the BoxProduction Time Profiling Out of the Box
Production Time Profiling Out of the Box
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
 
Head toward Java 14 and Java 15 #LINE_DM
Head toward Java 14 and Java 15 #LINE_DMHead toward Java 14 and Java 15 #LINE_DM
Head toward Java 14 and Java 15 #LINE_DM
 
Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015
 
JDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java SmallerJDK 9: Big Changes To Make Java Smaller
JDK 9: Big Changes To Make Java Smaller
 
JDK 9: Mission Accomplished. What Next For Java?
JDK 9: Mission Accomplished. What Next For Java?JDK 9: Mission Accomplished. What Next For Java?
JDK 9: Mission Accomplished. What Next For Java?
 
Intro To OSGi
Intro To OSGiIntro To OSGi
Intro To OSGi
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep Dive
 
Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]
Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]
Java Debuggers: A Peek Under the Hood [JavaOne 2016 CON1503]
 
Head toward Java 14 and Java 15
Head toward Java 14 and Java 15Head toward Java 14 and Java 15
Head toward Java 14 and Java 15
 
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
JIT Versus AOT: Unity And Conflict of Dynamic and Static Compilers (JavaOne 2...
 
Project Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To JavaProject Jigsaw in JDK 9: Modularity Comes To Java
Project Jigsaw in JDK 9: Modularity Comes To Java
 
What's New in Java 9
What's New in Java 9What's New in Java 9
What's New in Java 9
 

En vedette

Atomics, CAS and Nonblocking algorithms
Atomics, CAS and Nonblocking algorithmsAtomics, CAS and Nonblocking algorithms
Atomics, CAS and Nonblocking algorithmsAlexey Fyodorov
 
JDK: CPU, PSU, LU, FR — WTF?!
JDK: CPU, PSU, LU, FR — WTF?!JDK: CPU, PSU, LU, FR — WTF?!
JDK: CPU, PSU, LU, FR — WTF?!Alexey Fyodorov
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)RichardWarburton
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and FutureRichardWarburton
 
Hot and spicy Java with Lombok. Live!
Hot and spicy Java with Lombok. Live!Hot and spicy Java with Lombok. Live!
Hot and spicy Java with Lombok. Live!Vladimir Tsukur
 
Java compilers and IDEs
Java compilers and IDEsJava compilers and IDEs
Java compilers and IDEschashnikov
 
Serialization and performance in Java
Serialization and performance in JavaSerialization and performance in Java
Serialization and performance in JavaStrannik_2013
 
OOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applicationsOOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applicationsMikalai Alimenkou
 
Spring Boot. Boot up your development. JEEConf 2015
Spring Boot. Boot up your development. JEEConf 2015Spring Boot. Boot up your development. JEEConf 2015
Spring Boot. Boot up your development. JEEConf 2015Strannik_2013
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
WILD microSERVICES v2 (JEEConf Edition)
WILD microSERVICES v2 (JEEConf Edition)WILD microSERVICES v2 (JEEConf Edition)
WILD microSERVICES v2 (JEEConf Edition)Aleksandr Tarasov
 
Do we need JMS in 21st century?
Do we need JMS in 21st century?Do we need JMS in 21st century?
Do we need JMS in 21st century?Mikalai Alimenkou
 

En vedette (14)

Atomics, CAS and Nonblocking algorithms
Atomics, CAS and Nonblocking algorithmsAtomics, CAS and Nonblocking algorithms
Atomics, CAS and Nonblocking algorithms
 
JDK: CPU, PSU, LU, FR — WTF?!
JDK: CPU, PSU, LU, FR — WTF?!JDK: CPU, PSU, LU, FR — WTF?!
JDK: CPU, PSU, LU, FR — WTF?!
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
 
Hot and spicy Java with Lombok. Live!
Hot and spicy Java with Lombok. Live!Hot and spicy Java with Lombok. Live!
Hot and spicy Java with Lombok. Live!
 
Java compilers and IDEs
Java compilers and IDEsJava compilers and IDEs
Java compilers and IDEs
 
Why do I hate Hibernate?
Why do I hate Hibernate?Why do I hate Hibernate?
Why do I hate Hibernate?
 
Serialization and performance in Java
Serialization and performance in JavaSerialization and performance in Java
Serialization and performance in Java
 
OOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applicationsOOP paradigm, principles of good design and architecture of Java applications
OOP paradigm, principles of good design and architecture of Java applications
 
Scala Rock-Painting
Scala Rock-PaintingScala Rock-Painting
Scala Rock-Painting
 
Spring Boot. Boot up your development. JEEConf 2015
Spring Boot. Boot up your development. JEEConf 2015Spring Boot. Boot up your development. JEEConf 2015
Spring Boot. Boot up your development. JEEConf 2015
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
WILD microSERVICES v2 (JEEConf Edition)
WILD microSERVICES v2 (JEEConf Edition)WILD microSERVICES v2 (JEEConf Edition)
WILD microSERVICES v2 (JEEConf Edition)
 
Do we need JMS in 21st century?
Do we need JMS in 21st century?Do we need JMS in 21st century?
Do we need JMS in 21st century?
 

Similaire à CompletableFuture уже здесь

HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]
HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]
HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]David Buck
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJavaDayUA
 
"Quantum" Performance Effects
"Quantum" Performance Effects"Quantum" Performance Effects
"Quantum" Performance EffectsSergey Kuksenko
 
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]David Buck
 
Critical software developement
Critical software developementCritical software developement
Critical software developementnedseb
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterJAXLondon2014
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Simon Ritter
 
Capgemini oracle live-sql
Capgemini oracle live-sqlCapgemini oracle live-sql
Capgemini oracle live-sqlJohan Louwers
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerSteven Feuerstein
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
 
chapter4.ppt
chapter4.pptchapter4.ppt
chapter4.pptMalathyN6
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Thomas Wuerthinger
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8javafxpert
 
2015 JavaOne LAD JSF 2.3 & MVC 1.0
2015 JavaOne LAD JSF 2.3 & MVC 1.02015 JavaOne LAD JSF 2.3 & MVC 1.0
2015 JavaOne LAD JSF 2.3 & MVC 1.0mnriem
 
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)Shing Wai Chan
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDISven Ruppert
 

Similaire à CompletableFuture уже здесь (20)

Completable future
Completable futureCompletable future
Completable future
 
HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]
HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]
HotSpot Synchronization, A Peek Under the Hood [JavaOne 2015 CON7570]
 
JDK8: Stream style
JDK8: Stream styleJDK8: Stream style
JDK8: Stream style
 
JShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java PlatformJShell: An Interactive Shell for the Java Platform
JShell: An Interactive Shell for the Java Platform
 
"Quantum" Performance Effects
"Quantum" Performance Effects"Quantum" Performance Effects
"Quantum" Performance Effects
 
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
 
Critical software developement
Critical software developementCritical software developement
Critical software developement
 
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon RitterLambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
Lambdas and Streams in Java SE 8: Making Bulk Operations simple - Simon Ritter
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
 
Capgemini oracle live-sql
Capgemini oracle live-sqlCapgemini oracle live-sql
Capgemini oracle live-sql
 
Take Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL CompilerTake Full Advantage of the Oracle PL/SQL Compiler
Take Full Advantage of the Oracle PL/SQL Compiler
 
Interactive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and ArchitectureInteractive Java Support to your tool -- The JShell API and Architecture
Interactive Java Support to your tool -- The JShell API and Architecture
 
chapter4.ppt
chapter4.pptchapter4.ppt
chapter4.ppt
 
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
Graal and Truffle: Modularity and Separation of Concerns as Cornerstones for ...
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
Cool SQL Features
Cool SQL FeaturesCool SQL Features
Cool SQL Features
 
2015 JavaOne LAD JSF 2.3 & MVC 1.0
2015 JavaOne LAD JSF 2.3 & MVC 1.02015 JavaOne LAD JSF 2.3 & MVC 1.0
2015 JavaOne LAD JSF 2.3 & MVC 1.0
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
JavaOne San Francisco 2013 - Servlet 3.1 (JSR 340)
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
 

Dernier

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Dernier (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

CompletableFuture уже здесь

  • 1. CompletableFuture уже здесь Дмитрий Чуйко dmitry.chuyko@oracle.com Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved.
  • 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
  • 4. Введение Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/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
  • 8. Сложности: Обработка ошибок try { try { return parse(fileObject , content.get ()); } catch ( ExecutionException e) { unfold(e); } } catch ( IOException e) { log.error(e, fileObject ); } catch ( InterruptedException e) { throw new RuntimeException (e); } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/45
  • 9. Сложности: Обработка ошибок private static void unfold( ExecutionException e) throws IOException , InterruptedException { Throwable cause = e.getCause (); if (cause instanceof ExecutionException ) unfold (( ExecutionException ) cause ); if (cause instanceof IOException ) throw ( IOException) cause; if (cause instanceof InterruptedException ) throw ( InterruptedException ) cause; if (cause instanceof Error) throw (Error) cause; if (cause instanceof RuntimeException ) throw ( RuntimeException ) cause; throw new RuntimeException (e); } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 9/45
  • 10. Сложности: Давайте добавим обработчики! readFileAsync (file , content -> System.out.println(content), ex -> ex. printStackTrace (); ); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/45
  • 11. Сложности: Давайте добавим обработчики! readFileAsync (file , content -> System.out.println(content), ex -> ex. printStackTrace (); ); ∙ ↓Добро пожаловать сюда↓ http://callbackhell.com/ readFileAsync (file , content -> processContentAsync (content , c -> System.out.println(c), e -> e. printStackTrace () ); ex -> ex. printStackTrace (); ); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/45
  • 12. Сложности: Результат Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 11/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
  • 15. API Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 14/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
  • 20. Методы: Трансформации ∙ CompletableFuture<U> thenApply(Function<T,U> fn) – Нет "Async"→ продолжаем в том же потоке ∙ CompletableFuture<U> thenApplyAsync(Function<T,U> fn [, Executor executor]) Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 19/45
  • 21. Методы: Трансформации (map) CompletableFuture <Long > cf2 = CompletableFuture .supplyAsync (() -> 42L) .thenApply(r1 -> r1 + 2015); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 20/45
  • 22. Методы: Подписка ∙ CompletableFuture<Void> thenAccept(Consumer<T> block); ∙ CompletableFuture<Void> thenRun(Runnable action); ∙ Async versions CompletableFuture <Void > cf3 = CompletableFuture .supplyAsync (() -> 42L) .thenApply(r1 -> r1 + 2015) .thenAccept(System.out:: println ); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 21/45
  • 23. Методы: Обработка ошибок ∙ CompletableFuture<T> exceptionally(Function<Throwable, T> fn) ∙ CompletableFuture<U> handle(BiFunction<T, Throwable, U> fn) ∙ Ошибка пробрасывается по цепочкам CompletableFuture . supplyAsync (() -> readFile(file )) . thenComposeAsync (content -> processContent (content )) .thenAccept(System.out:: println) . exceptionally (Throwable :: printStackTrace ); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 22/45
  • 24. Методы: Обработка ошибок CompletableFuture <Void > cf = new CompletableFuture < >(); cf. completeExceptionally (new RuntimeException ()); //cf. completeExceptionally (new CompletionException (new RuntimeException ())); cf. exceptionally (e -> { System.out.println(e); return null; }); cf.thenApply(Function.identity ()). exceptionally (e -> { System.out.println(e); // CompletionException : RuntimeException - not this stage return null; }); cf.get (); // ExecutionException : RuntimeException Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 23/45
  • 25. Методы: Комбинация (reduce) ∙ CompletableFuture<V> thenCombine (CompletionStage<U> other, BiFunction<T,U,V> fn) CompletableFuture <Long > cf2 = CompletableFuture .supplyAsync (() -> 42L) .thenCombine ( CompletableFuture . supplyAsync (() -> 2015) , Math ::min); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 24/45
  • 26. Методы: Для набора ∙ CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) ∙ CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 25/45
  • 27. Методы: Композиция (flatMap) ∙ CompletableFuture<U> thenCompose(Function<T,CompletableFuture<U>> fn) CompletableFuture <Long > cff = CompletableFuture .supplyAsync (() -> 42L) .thenCompose (x -> CompletableFuture .supplyAsync (() -> x + 2015)); CompletableFuture <CompletableFuture <Long >> cff = CompletableFuture .supplyAsync (() -> 42L) .thenApply(x -> CompletableFuture . supplyAsync (() -> x + 2015)); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 26/45
  • 28. Методы: Get ∙ T get() throws InterruptedException, ExecutionException ∙ T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException ∙ T getNow(T valueIfAbsent) ∙ T join() – Нет checked exceptions (CompletionException) ... stream.map(x -> CompletableFuture ...). map( CompletableFuture :: join) ... Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 27/45
  • 29. Методы: Get // parallel where? stream.parallel () .map(x -> CompletableFuture .supplyAsync ...) .map( CompletableFuture :: join ); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/45
  • 30. Методы: Get // parallel where? stream.parallel () .map(x -> CompletableFuture .supplyAsync ...) .map( CompletableFuture :: join ); // NOT Executors. newSingleThreadExecutor (); ExecutorService es1 = new ForkJoinPool (1); Future <?> task1 = es1.submit (() -> { try { es1.submit (()-> System.out.println("1")). get (); } catch (Exception e) { } }); task1.get (); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/45
  • 31. Методы: Get // parallel where? stream.parallel () .map(x -> CompletableFuture .supplyAsync ...) .map( CompletableFuture :: join ); // NOT Executors. newSingleThreadExecutor (); ExecutorService es1 = new ForkJoinPool (1); Future <?> task1 = es1.submit (() -> { try { es1.submit (()-> System.out.println("1")). get (); } catch (Exception e) { } }); task1.get (); // parallel where? CompletableFuture . supplyAsync (() -> stream (). parallel ()... , fjpN ); Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/45
  • 32. Методы: Исполнение в потоках ∙ isDone() → исполнение метода в текущем потоке – Если не ...Async() – И для exceptionally() ∙ helpPostComplete() на любой чих помогаем будить ждущих – И для exceptionally() – И для повторных вызовов complete() Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 29/45
  • 33. Накладные расходы Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 30/45
  • 34. Бенчмарк: Окружение ∙ Intel Core i5-3320M (1x2x2, 3.3 GHz) ∙ Linux x64 (kernel 3.19) ∙ JDK 9 EA (b64) ∙ OpenJDK JMH 1.10-SNAPSHOT Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 31/45
  • 35. Бенчмарк: Базовые операции @Param ({ "1024" }) public volatile int loada; @Param ({ "1024" }) public volatile int loadb; Integer a() { Blackhole.consumeCPU(loada ); return loada; } Integer b() { Blackhole.consumeCPU(loadb ); return loadb; } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 32/45
  • 36. Бенчмарк: Что сравниваем Простой вариант @Benchmark public Integer ab() { return a() * b(); } @Benchmark public Integer stream () throws InterruptedException , ExecutionException { return IntStream.range (0, 2) .mapToObj ((i) -> i == 0 ? a() : b()) .reduce (1, (a, b) -> a * b); } @Benchmark public Integer parstream () throws InterruptedException , ExecutionException { return IntStream.range (0, 2). parallel () .mapToObj ((i) -> i == 0 ? a() : b()) .reduce (1, (a, b) -> a * b); } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 33/45
  • 37. Бенчмарк: Что сравниваем Future @Benchmark public Integer future2 () throws InterruptedException , ExecutionException { ExecutorService fjp = ForkJoinPool .commonPool (); Future <Integer > fa = fjp.submit (() -> a()); Future <Integer > fb = fjp.submit (() -> b()); return fa.get() * fb.get (); } @Benchmark public Integer future3 () throws InterruptedException , ExecutionException { ExecutorService fjp = ForkJoinPool .commonPool (); Future <Integer > fa = fjp.submit (() -> a()); Future <Integer > fb = fjp.submit (() -> b()); return fjp.submit (() -> fa.get() * fb.get ()). get (); } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 34/45
  • 38. Бенчмарк: Что сравниваем CompletableFuture @Benchmark public Integer cf2() throws InterruptedException , ExecutionException { return CompletableFuture . supplyAsync (() -> a()) .thenCombine ( CompletableFuture . supplyAsync (() -> b()), (a, b) -> a * b) .get (); } @Benchmark public Integer cf3() throws InterruptedException , ExecutionException { return CompletableFuture . supplyAsync (() -> a()) . thenCombineAsync ( CompletableFuture .supplyAsync (() -> b()), (a, b) -> a * b) .get (); } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 35/45
  • 39. Бенчмарк: Результаты Параметры по умолчанию (loada=loadb=1K) Вариант 𝜇c/оп ab 6 ± 1 cf2 4 ± 1 cf3 4 ± 1 future2 8 ± 1 future3 8 ± 1 parstream 7 ± 1 stream 6 ± 1 Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 36/45
  • 40. Бенчмарк: Результаты Оценка пустой операции (loada=loadb=0) Вариант Время, нc/оп Аллокации, B/оп ab 11 ± 1 0 ± 0 cf2 715 ± 11 200 ± 1 cf3 1060 ± 17 204 ± 2 future2 4733 ± 135 80 ± 1 future3 4657 ± 213 128 ± 1 parstream 421 ± 24 496 ± 1 stream 131 ± 1 248 ± 1 Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/45
  • 41. Бенчмарк: Результаты Долгая операция (loada=loadb=128K) Вариант 𝜇c/оп ab 713 ± 1 cf2 383 ± 8 cf3 393 ± 10 future2 386 ± 8 future3 387 ± 9 parstream 378 ± 10 stream 713 ± 1 Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 38/45
  • 42. Пример. Rest-сервис Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 39/45
  • 43. Сервис: Ингридиенты ∙ JDK 8u25 ∙ JAX-RS 2.0 https://jax-rs-spec.java.net/ ∙ Jersey RI https://jersey.java.net/ ∙ Grizzly NIO framework https://grizzly.java.net/ Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 40/45
  • 44. Сервис: Ингридиенты ∙ JDK 8u25 ∙ JAX-RS 2.0 https://jax-rs-spec.java.net/ ∙ Jersey RI https://jersey.java.net/ ∙ Grizzly NIO framework https://grizzly.java.net/ ∙ CompletableFuture Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 40/45
  • 45. Сервис: Запускалка public class Main { public static final String BASE_URI = "http :// localhost :8080/ jee/"; public static void main(String [] args) throws IOException { ResourceConfig rc = new ResourceConfig (). packages("com.oracle.demo"); HttpServer server = GrizzlyHttpServerFactory . createHttpServer (URI.create(BASE_URI), rc); System.out.println(String.format("Jersey␣app␣started␣" + "with␣WADL␣available␣at␣% sapplication .wadln" + "Hit␣enter␣to␣stop␣it...", BASE_URI )); System.in.read (); server.shutdownNow (); } } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 41/45
  • 46. Сервис: Endpoint @Path("jeeconf") public class JEEConf { @Inject DataService dataService ; // @ManagedAsync -- NOT NEEDED @GET @Produces(MediaType.TEXT_PLAIN) public void asyncGet(@Suspended final AsyncResponse asyncResponse ) { dataService . findAudience () . thenCombine( dataService. findImpression (), (a, b) -> a + b) .thenApply( asyncResponse :: resume) . exceptionally ( asyncResponse :: resume ); // way #1 asyncResponse .setTimeout (1, SECONDS ); asyncResponse . setTimeoutHandler (ar -> ar.resume(new TimeoutException ())); } } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 42/45
  • 47. Сервис: Provider Часть 1/2 @ManagedBean @Path("data") public class DataService { // @Inject ScheduledExecutorService shedPool = Executors. newScheduledThreadPool (1); public CompletableFuture <String > findAudience () { return find("audience"); } public CompletableFuture <String > findImpression () { return find("impression"); } @PreDestroy public void shutdown () { shedPool.shutdownNow (); } ... Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 43/45
  • 48. Сервис: Provider Часть 2/2 public CompletableFuture <String > find(String path) { CompletableFuture <String > promise = new CompletableFuture < >(); CompletableFuture .runAsync (() -> { try { promise.complete(new String(Files. readAllBytes (Paths.get(path )))); } catch ( IOException e) { promise. completeExceptionally (e); } }); // way #2. and impact on shedPool. shedPool.schedule( () -> promise. completeExceptionally (new TimeoutException ()), 1, SECONDS ); return promise; } } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 44/45
  • 49. Сервис: ExceptionMapper @Provider public class CompletionExceptionMapper implements ExceptionMapper <CompletionException > { public Response toResponse( CompletionException bex) { return Response.status(Status. BAD_REQUEST) .entity(new File("error.png")). type("image/png"). build (); } } Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 45/45