- Wrappers around the standard Java 8 functional interfaces to use with a context snapshot.
- A
ContextAwareCompletableFutureimplementation.
Add the following dependency to your classpath:
<dependency>
<groupId>nl.talsmasoftware.context</groupId>
<artifactId>context-propagation-java8</artifactId>
<version>[see maven-central version above]</version>
</dependency>By far the easiest use of the context propagation library is using the
ContextAwareExecutorService.
If that is not a possibility, the following java functional interface wrappers in this java 8 module may be of help to you:
The easiest use of the context propagation library is using the
ContextAwareExecutorService.
If that is not a possibility, you can use the following java functional interface wrappers that will apply a captured context snapshot to the wrapped function:
BiConsumerBiFunctionBinaryOperatorBiPredicateBooleanSupplierConsumerFunctionPredicateRunnableSupplierUnaryOperator
The CompletableFuture class was introduced in Java 8:
A
Futurethat may be explicitly completed (setting its value and status), and may be used as aCompletionStage, supporting dependent functions and actions that trigger upon its completion.
The context-aware completable future will propagate the context into most completion stage operations, in particular:
thenApplyand its async variantsthenAcceptand its async variantsthenRunand its async variantsthenCombineand its async variantsthenAcceptBothand its async variantsthenComposeand its async variantswhenCompleteand its async variantshandleand its async variantsexceptionallyrunAfterBothand its async variantsapplyToEitherand its async variantsacceptEitherand its async variantsrunAfterEitherand its async variants
When the order of stages is clearly defined (e.g. the thenXyz, whenComplete etc),
a new context snapshot can be taken between each stage by invoking the takeNewSnapshot()
before declaring the new stage. This takes a new snapshot after each completion stage and
propagates that to following stages.
The ContextAwareCompletableFutureTest class contains
test cases that demonstrate the behaviour of this complex class.
Please be aware that:
- in almost all circumstances it's preferable
to choose
ContextAwareExecutorServiceoverContextAwareCompletableFuture. - neither the standard
CompletableFuturenor this context-aware version will attempt to cancel or interrupt an ongoing process when cancelled.