why are struts Action classes not thread safe?

Vinoth Kumar C M picture Vinoth Kumar C M · Feb 17, 2011 · Viewed 22.6k times · Source

I can read in many websites that Struts Action classes are not thread safe . I am not able to understand why this is so .

Also I read a book which says "Struts action classes are cached and reused for performance optimization at the cost of having to implement the action classes in a thread-safe manner"

how is caching action classes and being thread safe related? .

Answer

Steven Benitez picture Steven Benitez · Feb 17, 2011

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.