com.alibaba.mtc.MtContextThreadLocal Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of multithread.context Show documentation
Show all versions of multithread.context Show documentation
a simple lib for transmitting context between thread even using thread pool.
package com.alibaba.mtc;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
/**
* {@link MtContextThreadLocal} can transmit context from the thread of submitting task to the thread of executing task.
*
* Note: this class extends {@link java.lang.InheritableThreadLocal},
* so {@link com.alibaba.mtc.MtContextThreadLocal} first is a {@link java.lang.InheritableThreadLocal}.
*
* @author ding.lid
* @see MtContextRunnable
* @see MtContextCallable
* @since 0.10.0
*/
public class MtContextThreadLocal extends InheritableThreadLocal {
/**
* Computes the context value for this multi-thread context variable
* as a function of the source thread's value at the time the task
* Object is created. This method is called from {@link com.alibaba.mtc.MtContextRunnable} or
* {@link com.alibaba.mtc.MtContextCallable} when it create, before the task is started.
*
* This method merely returns reference of its source thread value, and should be overridden
* if a different behavior is desired.
*
* @since 1.0.0
*/
protected T copy(T parentValue) {
return parentValue;
}
@Override
public final T get() {
T value = super.get();
if (null != value) {
addMtContextThreadLocal();
}
return value;
}
@Override
public final void set(T value) {
super.set(value);
if (null == value) { // may set null to remove value
removeMtContextThreadLocal();
} else {
addMtContextThreadLocal();
}
}
@Override
public final void remove() {
removeMtContextThreadLocal();
super.remove();
}
private void superRemove() {
super.remove();
}
T copyMtContextValue() {
return copy(get());
}
static ThreadLocal