Class MdcManager

  • All Implemented Interfaces:
    ContextManager<Map<String,​String>>

    public class MdcManager
    extends Object
    implements ContextManager<Map<String,​String>>
    Manager to propagate the MDC content from one thread to another.

    As MDC already manages its own threadlocal state, getting the active context is 100% delegated to the MDC.
    This means that closing the resulting context from getActiveContext() will have no side-effects, as it is not ours to manage.

    Closing a context returned form initializeNewContext(Map) will reset the MDC to the values it had before the context was created.
    This means that closing nested contexts out-of-order will probably result in an undesirable state.
    It is therefore strongly advised to use Java's try-with-resources mechanism to ensure proper closing when nesting new MDC contexts.

    Author:
    Sjoerd Talsma
    • Constructor Detail

      • MdcManager

        public MdcManager()
    • Method Detail

      • initializeNewContext

        public Context<Map<String,​String>> initializeNewContext​(Map<String,​String> mdcValues)
        Initializes a new MDC context populated by the specified values.

        The given values will become the active MDC values for the current thread.
        Closing the resulting context will restore the MDC to the state it had just before this call.

        Please be aware that this may overwrite changes made to the MDC from other code.

        Specified by:
        initializeNewContext in interface ContextManager<Map<String,​String>>
        Parameters:
        mdcValues - The values to initialize a new context for (which must be closed by the caller at the end of its lifecycle).
        Returns:
        A context that -when closed- will restore the active MDC values to what they were just before this call.
      • getActiveContext

        public Context<Map<String,​String>> getActiveContext()
        Returns the active MDC values from the current thread.

        Please note: Because these values are managed by MDC itself and not by us, closing the resulting context has no effect.

        Specified by:
        getActiveContext in interface ContextManager<Map<String,​String>>
        Returns:
        Context containing the active MDC values.