com.xiongyingqi.common.utils.context.Context Maven / Gradle / Ivy
The newest version!
package com.xiongyingqi.common.utils.context;
import java.util.HashMap;
import java.util.Map;
/**
* @author xiongyingqi
* @since 17-5-11 下午8:42
*/
class Context {
private volatile Class clazz;
private static Map, ThreadLocal>> classThreadLocalMap = new HashMap, ThreadLocal>>();
public Context(Class clazz) {
this.clazz = clazz;
}
@SuppressWarnings("unchecked")
protected T getContext() {
ThreadLocal> threadLocal = classThreadLocalMap.get(clazz);
if (threadLocal == null) {
return null;
}
return (T) threadLocal.get();
}
@SuppressWarnings("unchecked")
protected void setContext(final T instance) {
ThreadLocal threadLocal = (ThreadLocal) classThreadLocalMap.get(clazz);
if (threadLocal == null) {
synchronized (clazz) {
threadLocal = new ThreadLocal() {
@Override
protected T initialValue() {
return instance;
}
};
classThreadLocalMap.put(clazz, threadLocal);
}
}
threadLocal.set(instance);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy