I have a question about writing thread-safe Actions.
I just recently discovered that Struts creates only one instance of the Action object for multiple sessions, and having a global variable in your Action objects makes your code not thread-safe. This was after I realized that my application was behaving quite differently when multiple users are using the application, and the pages are messed up.
So I am thinking of making some code refactoring to make the code thread-safe. The structure of my code is simple: I have a BaseAction class from which the other Action classes are extended. Here's the current code:
I already removed some of the global variables that used to be in the BaseAction class, but the application is still behaving differently in multiple sessions.
So my first question is: Is the current structure of my code not thread-safe? And, how can I refactor the code to make it thread-safe?
Thanks in advance,
There's so much to learn in this industry, and not everybody has the necessary interest.
Joined: Jan 28, 2008
I do believe that your code is totally not thread safe, and the reason is that you are using instance variables for request, response, mapping & form. You should ditch the execute method that you have in the BaseAction class completely, and override the execute method in all your extended actions. If you need to have a common behavior to be done before executing your action, you can simply put a method in the BaseAction that has this behavior, and call it from the extended actions.
Yep�I agree with the response by Alaa�having instance variables in your action class are a no-no with Struts. You can pass stuff around as parameters (like Struts does). You can have final instance variables, but that can only be used for stuff that would not change between instances. For example you might have a final logger class, but stuff like the form and request should not be stored in instance variables.
If you are trying to clean up the method signatures of your base class, you can wrap the parameter in a class that you pass around. For example this example uses a class named ActionParams (which is a class you would have to write):
Joined: May 18, 2006
Thanks for your inputs. At first, I was suspecting that those instance variables were the culprit, but it turns out that my problem was caused by a different bug. However I followed your suggestion and I removed all those instance variables from the BaseAction class entirely.