I’ve seen this pattern used in a few different places now, but I’m not sure exactly what it’s for or why it’s needed. Given that I have seen it in quality projects, I’m sure it’s useful, but I’d like to understand it rather than just blindly following it. I’ve specifically seen this pattern in Servlet Filters and Struts2 Interceptors (very similar in concept to a Filter).
Here’s an example from Google Guice (Servlet) 3.0:
Context previous = localContext.get();
try {
localContext.set(new Context((HttpServletRequest) servletRequest,
(HttpServletResponse) servletResponse));
//dispatch across the servlet pipeline, ensuring web.xml's filterchain is honored
filterPipeline.dispatch(servletRequest, servletResponse, filterChain);
} finally {
localContext.set(previous);
}
What is the need or benefit for restoring the value in the finally block?
It’s basically a way of scoping the changes only to the
tryblock. Regardless of whether or not the block successfully executes, you know that once you’re out of it, you have restored the value to what it was when you went in.