Last active
August 29, 2015 14:14
-
-
Save ogregoire/cc9b6eef05386f43c8fa to your computer and use it in GitHub Desktop.
Proper ThreadLocal usage
This file contains 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
import java.util.concurrent.Callable; | |
import javax.annotation.concurrent.ThreadSafe; | |
@ThreadSafe | |
public final class ThreadContext { | |
private static final ThreadLocal<Context> CONTEXT = new ThreadLocal<>(); | |
private ThreadContext() { | |
} | |
public static void runInContext(Context context, Runnable runnable) { | |
setUp(context); | |
try { | |
runnable.run(); | |
} finally { | |
tearDown(); | |
} | |
} | |
public static <T> T callInContext(Context context, Callable<T> callable) | |
throws Exception { | |
setUp(context); | |
try { | |
return callable.call(); | |
} finally { | |
tearDown(); | |
} | |
} | |
private static void setUp(Context context) { | |
if (context == null) { | |
throw new NullPointerException("context must not be null"); | |
} | |
if (getCurrentContext() != null) { | |
throw new IllegalStateException("The context is already set up"); | |
} | |
setCurrentContext(context); | |
} | |
private static void tearDown() { | |
if (getCurrentContext() == null) { // Should never happen | |
throw new IllegalStateException("The context is already torn down"); | |
} | |
setCurrentContext(null); | |
} | |
public static Context getCurrentContext() { | |
return CONTEXT.get(); | |
} | |
private static void setCurrentContext(Context context) { | |
CONTEXT.set(context); | |
} | |
} |
This file contains 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 Context { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment