9

I am writing an Jersey Response filter. I am using Jersey 1.17. I want to get access to some attributes of the httpServletRequest in the filter API. The way what i am doing right now is as below. Is it safe to inject the servletRequest like in the snippet below or will this cause some kind of concurrency issues? If there are multiple requests coming in conncurrently, will the servletRequest in different requests overwrite each other? Thanks for your hlep.

public class LoggingFilter implements ContainerResponseFilter {
@Context private HttpServletRequest servletRequest;
@Override
public ContainerResponse filter(final ContainerRequest req, final ContainerResponse resp) {
String s =  this.servletRequest.getAttribute("xxx");
....
}
}
lorcel
  • 315
  • 1
  • 3
  • 12

2 Answers2

8

You're safe. When you're injecting HttpServletRequest / HttpServletResponse you're not dealing with a particular instance but rather with a proxy through which you're invoking calls on a real instance stored in a ThreadLocal object. Each request is processed by a separate thread which has access to it's own HttpServletRequest / HttpServletResponse. Beside injecting HttpServletRequest / HttpServletResponse you can also inject ThreadLocal<HttpServletRequest> / ThreadLocal<HttpServletResponse> and through '#get()` method you can obtain the real request / response instances intead of proxies.

Michal Gajdos
  • 10,339
  • 2
  • 43
  • 42
  • 1
    Thank you Michal. Actually I didn't expect people would answer my question so fast. This really surprised me and solve the problem. – lorcel Aug 20 '13 at 17:15
8

Section 9.1 (latest, 5.1 previously) Concurrency of the JAX-RS specification states:

Context is specific to a particular request but instances of certain JAX-RS components (providers and resource classes with a lifecycle other than per-request) may need to support multiple concurrent requests. When injecting an instance of one of the types listed in Section 9.2, the instance supplied MUST be capable of selecting the correct context for a particular request. Use of a thread-local proxy is a common way to achieve this.

So, as per the specification, JAX-RS implementations (e.g. Jersey) are required to ensure that the context is safe. Keep doing what you're doing.

See also: Extract request attributes from container request of Jersey

Community
  • 1
  • 1
DannyMo
  • 11,344
  • 4
  • 31
  • 37
  • 1
    Thank you so much. I didn't expect people would answer my question so fast. This really surprised me and solve the problem. – lorcel Aug 20 '13 at 17:15