Interface Context<T>

  • All Superinterfaces:
    AutoCloseable, Closeable
    All Known Implementing Classes:
    AbstractThreadLocalContext

    public interface Context<T>
    extends Closeable
    A context can be anything that needs to be maintained on the 'current thread' level.

    It is the responsibility of the one activating a new context to also close it again from the same thread.

    Implementations are typically maintained within a static ThreadLocal variable.
    A context has a very simple life-cycle: they can be created and closed. A well-behaved Context implementation will make sure that thread-local state is restored to the way it was before when the context gets closed again.
    There is an abstract implementation available that can be extended, that takes care of random-depth nested contexts and restoring the 'previous' context state.

    Author:
    Sjoerd Talsma
    • Method Detail

      • getValue

        T getValue()
        Returns the value associated with this context.

        Implementors should explicitly document the behaviour of this method after close() was called. For example, it may be useful to always return null after a Context has been closed. Contrary, it may in some cases be useful to retain the existing value after the context is closed, so clients that have kept a reference can still have access to it.

        Normally, for security-related contexts, it is wise to always return null from closed contexts.

        Returns:
        The value associated with this context.
      • close

        void close()
        Closes this context.

        It is the responsibility of the one activating a new context to also close it again from the same thread.

        It must be possible to call this method multiple times. It is the responsibility of the implementor of this context to make sure that closing an already-closed context has no unwanted side-effects. A simple way to achieve this is by using an AtomicBoolean to make sure the 'closing' transition is executed only once.

        Implementors should attempt to restore previous contextual state upon close.

        Specified by:
        close in interface AutoCloseable
        Specified by:
        close in interface Closeable
        Throws:
        RuntimeException - if an error occurs while restoring the context.