Skip to content

Instantly share code, notes, and snippets.

@ogregoire
Last active August 29, 2015 14:14
Show Gist options
  • Save ogregoire/cc9b6eef05386f43c8fa to your computer and use it in GitHub Desktop.
Save ogregoire/cc9b6eef05386f43c8fa to your computer and use it in GitHub Desktop.
Proper ThreadLocal usage
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);
}
}
public class Context {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment