Skip to content

Instantly share code, notes, and snippets.

@nschlimm
Created March 29, 2012 07:13
Show Gist options
  • Save nschlimm/2234464 to your computer and use it in GitHub Desktop.
Save nschlimm/2234464 to your computer and use it in GitHub Desktop.
ThreadLocalUtil
public class ThreadLocalUtil {
private final static ThreadLocal<ThreadVariables> THREAD_VARIABLES = new ThreadLocal<ThreadVariables>() {
/**
* @see java.lang.ThreadLocal#initialValue()
*/
@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();
}
@saikiran939
Copy link

Simple and Elegant - thanks for sharing.

@dmaidaniuk
Copy link

Hi Niklas,

Good job! I'm going to reuse your idea in Ozark - Java EE MVC RI. Hope that you don't have any objections for this.

Regards,
Dmytro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment