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 andclosed
. A well-behavedContext
implementation will make sure that thread-local state is restored to the way it was before when the context getsclosed
again.
There is anabstract implementation
available that can be extended, that takes care of random-depth nested contexts and restoring the 'previous' context state.- Author:
- Sjoerd Talsma
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description void
close()
Closes this context.T
getValue()
Returns the value associated with this context.
-
-
-
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 returnnull
after aContext
has beenclosed
. Contrary, it may in some cases be useful to retain the existingvalue
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 interfaceAutoCloseable
- Specified by:
close
in interfaceCloseable
- Throws:
RuntimeException
- if an error occurs while restoring the context.
-
-