Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 547
peanut_butter Avatar asked Oct 31 '25 06:10

peanut_butter


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
like image 60
Kavithakaran Kanapathippillai Avatar answered Nov 02 '25 19:11

Kavithakaran Kanapathippillai