why are struts Action classes not thread safe?

How is caching action classes and being thread safe related?

If you cache and re-use instances of a class, allowing multiple threads to access the same instance simultaneously, then the class is inherently not thread-safe*. If you were to place mutable instance or static fields on the class, the results under concurrency would be unexpected and problematic. On the other hand, if each thread has its own instance of the class, then the class is inherently thread-safe.

  • Struts 1 action classes are not thread-safe. You should not place any mutable fields on the class, instead using a Form Bean class for form fields passed to the action.
  • Struts 2 action classes are thread-safe. New copies are instantiated for each request and placing instance fields on the class is a core concept in the framework.

* If the instance or static field is immutable, then its fine for multiple threads to access it simultaneously.


if any class is cached, and reused, there is a risk of corruption do to concurrent accesses by multiple threads. In a web application, every request is handled on a thread. Lets say you have 10 instances of an action, but your container is handling 20 requests -- in this case, your 10 actions are each being reused, because you have more requests in flight than actions available to service them.

The thread safety issue only rears its head if there is some state that is reused in the action. If that is the case, then an action that is servicing one request might set a value in the shared variable, but then another thread might take over, and the action might again modify the shared variable. In that case, when the original thread takes over, the shared state has been modified.

The easy way to deal with this is to configure your stack to just always use a new action, or make sure you have no shared state in your actions.


Why not create a new "action" object per request? What in the world??

Because Struts is so old, he thinks creating one more object per request cycle is as expensive as paying a dollar for a coffee. (that is, very expensive. because he's really old.)