Original Pattern: ServletRequest in ThreadLocal

After seeing Scala had elements of Erlang through Actors, I decided to take a closer look at the language. There is an interesting new web framework in Scala, called Lift. One drawback of Lift is that it seems to be very cutting edge and not that easy to grasp. While reading its source code, I stumbled upon a strange pattern: Storing the ServletRequest in a ThreadLocal.

I had not seen that before, and was wondering why one would do such a thing. It seems to be unintuitive. I found my answer through… GWT widgets. In this page, the author explain motivations behind doing such a thing:

While not 100% in tune with the MVC pattern, it is often convenient to access the servlet container, the HTTP session or the current HTTP request from the business layer. The GWT-SL provides several strategies to achieve this which pose a compromise in the amount of configuration required to set up and the class dependencies introduced to the business code. The easiest way to obtain the current HTTP request is by using the ServletUtils class which provides convenience methods for accessing the HttpServletRequest and HttpServletResponse instances. Please note that it makes use of thread local variables and will obviously not return correct values if used in any other than the invoking thread.

Still one can doubt if this is good design. In my long experience of web apps in Java I never had the need to do such a thing. Have you seen that pattern before?

Comments

comments powered by Disqus