"are interceptors in struts2 thread unsafe?" Code Answer


any interceptor that does not use instance fields or other shared state is thread-safe:

for examples, look at all the built-in interceptors that parse http request parameters and cookies, do logging, access checks, exception handling: they do not use instance fields for mutable state(*) but just operate on the actioninvocation instance they get as parameters.

(*) some do have instance fields for configuration parameters which are set when struts starts up (in a single thread), like exceptionmappinginterceptor, or thread-safe instance fields like the logger in logginginterceptor.

if you plan on writing your own interceptor, work just with the actioninvocation parameter you get passed in and with local variables in your intercept() method. avoid the temptation to make your intercept method synchronized or put things into a synchronized{} block -- this will create a bottleneck with struts' single-instance approach to interceptors.

to answer the questions from the comments:

(1) how come creating an instance of action for every thread doesn't affect the performance?or does it?

with modern jvms, the cost of creating an object is negligible. there should be no noticeable effect on performance if you keep your actions light-weight by avoiding expensive initializtion, e.g. by not creating database connections inside an action but using a connection pool.

(2) do u recommend never to use the default interceptor stack, and always use custom interceptor stack (where all the unused interceptors which use instance variables are removed) so that it will be thread safe?

i don't think any of the default interceptors that are shipped and configured with struts 2 are not thread-safe; even if they use instance fields (because they're either used for configuration only or itself thread-safe like logger).

from my personal experience, you should only ever touch/change the interceptor stack if you have a good reason (thread-safety of the built-in interceptors isn't one). a lot of things behave/break in unexpected ways if you change the stacks -- running one of the built-in stacks like "default" or "paramprepareparam" saves a lot of frustration in the long run. adding your own custom interceptors is usually less disruptive than removing/rearranging interceptors from an existing stack.

By Tobias Lins on June 4 2022

Answers related to “are interceptors in struts2 thread unsafe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.