@ThreadSafe public class ThreadContext extends Object
Map-like functions to keep track of key/value pairs for application threads. Keys are Strings, with values of any arbitrary object. Optionally keeps a log framework's MDC weakly in sync with changes -- that is, there is no atomicity guarantee so it's plausible that this class' context information and the logger's will not be in a consistent state; however, log4j and logback's MDC expose data only to the current thread via a thread-local so this is unlikely to be a problem in practice.
Most methods operate on the context of the calling thread; only
forThread(Thread)
allows cross-thread information retrieval.
Modifier and Type | Class and Description |
---|---|
static class |
ThreadContext.Log4jMdcBridge |
static interface |
ThreadContext.MdcBridge |
static class |
ThreadContext.NullMdcBridge |
static class |
ThreadContext.Slf4jMDCBridge |
Constructor and Description |
---|
ThreadContext() |
ThreadContext(ThreadContext.MdcBridge mdcBridge) |
Modifier and Type | Method and Description |
---|---|
Collection<String> |
allKeys() |
void |
clear()
Clears all values for the current thread.
|
Map<String,Object> |
forThread(Thread t)
Retrieves a copy of the thread context for the given thread
|
Object |
get(String key)
Retrieves the value corresponding to the supplied key for the current thread (null if no such
value exists)
|
Object |
getForThread(Thread thread,
String key) |
static ThreadContext |
newMDCEnabledContext()
Factory method that creates a new ThreadContext initialized to also update Log4j's MDC.
|
static ThreadContext |
newSLF4JEnabledContext()
Factory method that creates a new ThreadContext initialised to also update SLF4J's MDC
|
void |
put(String key,
Object value)
Adds the given key/value pair to the current thread's context, and updates
ThreadContext.MdcBridge with
same. |
void |
remove(String key)
Removes the given key from the current thread's context and
ThreadContext.MdcBridge . |
public ThreadContext()
public ThreadContext(ThreadContext.MdcBridge mdcBridge)
public void put(String key, Object value)
ThreadContext.MdcBridge
with
same.public void remove(String key)
ThreadContext.MdcBridge
.public Object get(String key)
public void clear()
public Map<String,Object> forThread(Thread t)
public Collection<String> allKeys()
public static ThreadContext newMDCEnabledContext()
public static ThreadContext newSLF4JEnabledContext()
Copyright © 2009–2019 Performance Co-Pilot. All rights reserved.