Which HandlerInterceptorAdapter method should be implemented and used to clear ThreadLocal?

Viewed 231

I have written an implementation of HandlerInterceptorAdapter. It is putting some request specific data in a ThreadLocal. Because threads are reused for new requests the data that was put in the ThreadLocal has to be removed when request is handled. Which HandlerInterceptorAdapter method should I implement to clear it? There are two options as I see it, postHandle and afterCompletion. I need that data in the ThreadLocal is guaranteed to be removed.

1 Answers

Use the afterCompletion. It will be called on any outcome

Callback after completion of request processing, that is, after rendering the view. Will be called on any outcome of handler execution, thus allows for proper resource cleanup.

Reference

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html

Note

  • If you are going to return false from from preHandle you should clean up thread local in the pre handle itself because false means you have handled the response, as a result postHanlde() or afterCompletion will not be called
Related