Interface ContextStorage


  • public interface ContextStorage
    The storage for storing and retrieving the current Context.

    If you want to implement your own storage or add some hooks when a Context is attached and restored, you should use ContextStorageProvider. Here's an example that sets MDC before Context is attached:

    
     > public class MyStorage implements ContextStorageProvider {
     >
     >   @Override
     >   public ContextStorage get() {
     >     ContextStorage threadLocalStorage = ContextStorage.defaultStorage();
     >     return new RequestContextStorage() {
     >       @Override
     >       public Scope T attach(Context toAttach) {
     >         Context current = current();
     >         setMdc(toAttach);
     >         Scope scope = threadLocalStorage.attach(toAttach);
     >         return () -> {
     >           clearMdc();
     >           setMdc(current);
     >           scope.close();
     >         }
     >       }
     >
     >       @Override
     >       public Context current() {
     >         return threadLocalStorage.current();
     >       }
     >     }
     >   }
     > }
     
    • Method Detail

      • addWrapper

        static void addWrapper​(Function<? super ContextStorage,​? extends ContextStorage> wrapper)
        Adds the wrapper, which will be executed with the ContextStorage is first used, i.e., by calling Context.makeCurrent(). This must be called as early in your application as possible to have effect, often as part of a static initialization block in your main class.
      • attach

        Scope attach​(Context toAttach)
        Sets the specified Context as the current Context and returns a Scope representing the scope of execution. Scope.close() must be called when the current Context should be restored to what it was before attaching toAttach.
      • root

        default Context root()
        Returns the root Context which all other Context are derived from.

        The default implementation returns the root ArrayBasedContext, but subclasses can override this method to return a root instance of a different Context implementation.