Interface CapturedContextProvider

All Known Implementing Classes:
DefaultMdcCapturedContextProvider, MdcCapturedContextProvider, OtelCapturedContextProvider

public interface CapturedContextProvider
Functionality related to capturing thread-local like context for later restoration across async boundaries.

If you want to capture any external state you can create a wrapper CapturedContext to add additional state capturing to the context pathway. This state can then be restored by wrapping the CapturedContext with the additional functionality to restore and finally revert the context state.

An example provider may be implemented as follows:


     private class CapturedContextImpl implements CapturedContext {
         private final CapturedContext delegate;
         private final String state;

         public Scope attachContext() {
             String old = getMyString();
             setMyString(state);
             Scope outer = delegate.attachContext();
             return () -> {
                 outer.close();
                 setMyString(old);
             };
         }

         public ContextMap captured() {
             return delegate.captured();
         }
     }

     private MyState getMyState() {
         // capture context state from the local environment
     }

     private void setMyState(MyState myState) {
         // set the context state in the local environment
     }

     CapturedContext captureContext(CapturedContext underlying) {
          return new CapturedContextImpl(delegate, getMyState());
     }

     CapturedContext captureContextCopy(CapturedContext underlying) {
          return new CapturedContextImpl(delegate, getMyState().copy());
     }
 
Note: If the MyState type is immutable then there is no distinction between captureContext(..) and captureContextCopy(..)
  • Method Details

    • captureContext

      CapturedContext captureContext(CapturedContext underlying)
      Capture a reference to existing context in preparation for an asynchronous boundary jump.
      Parameters:
      underlying - additional context that must be utilized as part of the returned CapturedContext, usually wrapped as described above.
      Returns:
      the wrapped CapturedContext.
    • captureContextCopy

      CapturedContext captureContextCopy(CapturedContext underlying)
      Capture a copy of existing context in preparation for an asynchronous boundary jump.
      Parameters:
      underlying - additional context that must be utilized as part of the returned CapturedContext, usually wrapped as described above.
      Returns:
      the wrapped CapturedContext.