Web项目中的ThreadLocal

12-10-11 banq
Threading stories: ThreadLocal in web applications - Java Code Geeks

将所有ThreadLocal 放入一个Wrapper中,防止内存泄漏,这样在Web容器undeploy时,通过 ServletRequestListener -> requestDestroyed() 调用该类的destroy()即可销毁所有的ThreadLocal变量:


public class ThreadLocalUtil {

private final static ThreadLocal<ThreadVariables> THREAD_VARIABLES = new ThreadLocal<ThreadVariables>() {

/**
* @see java.lang.ThreadLocalinitialValue()
*/
@Override
protected ThreadVariables initialValue() {
return new ThreadVariables();
}
};

public static Object getThreadVariable(String name) {
return THREAD_VARIABLES.get().get(name);
}

public static Object getThreadVariable(String name, InitialValue initialValue) {
Object o = THREAD_VARIABLES.get().get(name);
if (o == null) {
THREAD_VARIABLES.get().put(name, initialValue.create());
return getThreadVariable(name);
} else {
return o;
}
}

public static void setThreadVariable(String name, Object value) {
THREAD_VARIABLES.get().put(name, value);
}

public static void destroy() {
THREAD_VARIABLES.remove();
}
}

public class ThreadVariables extends HashMap<String, Object> { }

public abstract class InitialValue {

public abstract Object create();

}

[该贴被banq于2012-10-11 15:28修改过]

猜你喜欢