Skip to content

Latest commit

 

History

History
94 lines (72 loc) · 5.34 KB

File metadata and controls

94 lines (72 loc) · 5.34 KB

Released Version

Context propagation (Java 8)

How to get this module

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>

Applicability

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:

Functional interfaces

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:

ContextAwareCompletableFuture

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 a CompletionStage, 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 variants
  • thenAccept and its async variants
  • thenRun and its async variants
  • thenCombine and its async variants
  • thenAcceptBoth and its async variants
  • thenCompose and its async variants
  • whenComplete and its async variants
  • handle and its async variants
  • exceptionally
  • runAfterBoth and its async variants
  • applyToEither and its async variants
  • acceptEither and its async variants
  • runAfterEither and its async variants

Completion stages

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.

Caveats

Please be aware that:

  1. in almost all circumstances it's preferable to choose ContextAwareExecutorService over ContextAwareCompletableFuture.
  2. neither the standard CompletableFuture nor this context-aware version will attempt to cancel or interrupt an ongoing process when cancelled.