Web專案中的ThreadLocal

banq發表於2012-10-11
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修改過]

相關文章