Thread Local Context Pattern

aka Thread Local Global Variables


class RequestContextHolder {
	private static ThreadLocal threadLocal = new ThreadLocal();
	public static Map get() {
		return (Map)threadLocal.get();
	}
	public static void set(Map context) {
		threadLocal.set(context);
	}
	public static void clearContext() {
		threadLocal.set(null); }
	}
}

class FrontController
{
	public void handleReqeuest(HttpRequst request.....) {
		try {
			Map requestContext = buildRequestContext(request);
			RequestContextHolder.set(requestContext); .....
			Response response = handleRequest(request);
			processResponse(response);
		} finally {
			RequestContextHolder.clearContext();
		}
	}
}

Advertisements