- Wrappers around the standard Java 8 functional interfaces to use with a context snapshot.
- A
ContextAwareCompletableFuture
implementation.
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:
BiConsumer
BiFunction
BinaryOperator
BiPredicate
BooleanSupplier
Consumer
Function
Predicate
Runnable
Supplier
UnaryOperator
The CompletableFuture
class was introduced in Java 8:
A
Future
that 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:
thenApply
and its async variantsthenAccept
and its async variantsthenRun
and its async variantsthenCombine
and its async variantsthenAcceptBoth
and its async variantsthenCompose
and its async variantswhenComplete
and its async variantshandle
and its async variantsexceptionally
runAfterBoth
and its async variantsapplyToEither
and its async variantsacceptEither
and its async variantsrunAfterEither
and 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
ContextAwareExecutorService
overContextAwareCompletableFuture
. - neither the standard
CompletableFuture
nor this context-aware version will attempt to cancel or interrupt an ongoing process when cancelled.