In Struts, when using an ActionForm, are the instance variables thread safe? I'm reading Head First Servlets and JSP and on page 740 the BeerSelectForm which extends ActionForm has an instance variable named color.
Does Struts create a new instance of an ActionForm each time or does it just create one instance for the life of the app (like a servlet)? If it does not create a new instance of ActionForm for every request then I would think that the value of the instance variable could be changed by other threads between the getter and setter methods.
I can't find anything else on the web addressing this, other than on the Struts site itself it advises treating Action classes as non thread safe and use the same practice you would on servlets (ie; don't use instance variables unless you understand they are not thread safe).
But I'm probably missing something, as I am new to Struts.
Form beans and their associated actions are declared in the struts-config.xml file. The form beans are declared in the <form-bean> tag. These are given a name which is used in the <action> tags. The actions of the webapp may be associated with a form bean by declaring the 'name' attribute, which must match a form bean name declared above.
OK, that's how beans are associated with actions. The key to your question on thread-saftey is answered by another attribute in the <action> tag. The 'scope' attribute may be either 'request' or 'session'. If the scope is request, then the Strut's request processor will create a new bean for each request. In this case, access to the bean attributes is thread-safe, unless you created your own thread and pasted the bean to that thread (use with extreme caution).
If the scope is declared to be session, then the form bean is created when it is first needed (by some action) and then potentially accessed by subsequent requests (to actions that also use this form bean). For a discussion of why session scoped attributes are not thread-safe, please read HF-Servlets pg 198. If you really need to code a thread-safe, session-scoped form bean, then I would recommend the simple approach of synchronizing the public methods, including accessor and mutator methods.