Created
March 29, 2012 07:13
-
-
Save nschlimm/2234464 to your computer and use it in GitHub Desktop.
ThreadLocalUtil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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