
com.alibaba.ttl.TransmittableThreadLocal Maven / Gradle / Ivy
Show all versions of transmittable-thread-local Show documentation
package com.alibaba.ttl;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
/**
* {@link TransmittableThreadLocal} can transmit value from the thread of submitting task to the thread of executing task.
*
* Note: this class extends {@link java.lang.InheritableThreadLocal},
* so {@link TransmittableThreadLocal} first is a {@link java.lang.InheritableThreadLocal}.
*
* @author Jerry Lee (oldratlee at gmail dot com)
* @see TtlRunnable
* @see TtlCallable
* @since 0.10.0
*/
public class TransmittableThreadLocal extends InheritableThreadLocal {
/**
* Computes the value for this transmittable thread-local variable
* as a function of the source thread's value at the time the task
* Object is created. This method is called from {@link TtlRunnable} or
* {@link TtlCallable} 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;
}
/**
* Callback method before task object({@link TtlRunnable}/{@link TtlCallable}) execute.
*
* Default behavior is do nothing, and should be overridden
* if a different behavior is desired.
*
* Do not throw any exception, just ignored.
*
* @since 1.2.0
*/
protected void beforeExecute() {
}
/**
* Callback method after task object({@link TtlRunnable}/{@link TtlCallable}) execute.
*
* Default behavior is do nothing, and should be overridden
* if a different behavior is desired.
*
* Do not throw any exception, just ignored.
*
* @since 1.2.0
*/
protected void afterExecute() {
}
@Override
public final T get() {
T value = super.get();
if (null != value) {
addValue();
}
return value;
}
@Override
public final void set(T value) {
super.set(value);
if (null == value) { // may set null to remove value
removeValue();
} else {
addValue();
}
}
@Override
public final void remove() {
removeValue();
super.remove();
}
private void superRemove() {
super.remove();
}
T copyValue() {
return copy(get());
}
static ThreadLocal