jay electricity
jay electricity

Reputation: 309

Using Server Request and Response filters for ThreadLocal storage in a RestEasy based service

I am currently working on a RESTeasy based RESTful service. I have a filter class which serves as a server request filter as well as a server response filter (i.e. it implements ContainerRequestFilter and ContainerResponseFilter interfaces).

At the beginning of the request, I use the filter to put an object into ThreadLocal. This object is used by the resources throughout the request. At the end of the request, before sending out the response, the filter removes the object from ThreadLocal.

My question is that is there a guarantee that the the request filter, the resource and the response filter will all execute in the same thread? Is there a possibility that after the request filter puts the object into ThreadLocal, a different thread will execute the request (and thus not have access to the object)?

I was sure that this was the case but then I saw this http://jersey.576304.n2.nabble.com/Does-filter-method-of-ContainerRequestFilter-run-in-resource-method-thread-td7582648.html (official Jersey forum) and now I have doubts.

Upvotes: 6

Views: 2331

Answers (1)

Dirk Schumacher
Dirk Schumacher

Reputation: 1655

javax.ws.rs.container.ContainerRequestContext.setProperty(...)

and

javax.ws.rs.container.ContainerRequestContext.getProperty(...)

are probably the right approach. The javadoc states:

In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest.

Upvotes: 3

Related Questions