Tuesday, January 11, 2005

Java Tip #3 - Don't use fields on Struts action classes

This is very specific to the Struts web application framework. Don't use a field on a Struts action class. Struts caches action classes & reuses them to call the execute() method. (perform() on 1.0) This can cause unexpected behavior & performance issues under a load. Add a check for this to your code review process.

Thanks to the anonymous person who pointed out even without the 'static' modifier, this is a bad idea. Unless the field is marked as final, just don't do it.




4 Comments:

Anonymous Anonymous said...

You mean, don't use fields at all on actions.

1:23 PM  
Blogger Billy Bob Bain said...

You are right. Even a vanilla non-static field would cause problems.

3:54 PM  
Anonymous Anonymous said...

Can you pls. describe the problem in more detail? Can't you just make access to the field thread safe?

7:43 AM  
Blogger Billy Bob Bain said...

I have found that some developers don't know that they are sharing the action instance. They have their own form bean instance per request, but only one action instance.

If you're just going to synchronize access to the field, then you still have a potential performance problem.

Using one of the thread safe classes in the java.util.concurrent packages such as ConcurrentHashMap should be fine. But if you get blocking or an out of order update then your back to a performance problem or inconsistent data.

Since it's easy to screw up, I normally avoid adding fields to an action class altogether. At the framework level I might add a field to reference a common service, such as a cache. But I'd never put a field on the action class that had something to do with the business process I was solving.

9:16 AM  

Post a Comment

<< Home