Search This Blog

Thursday, October 22, 2009

J2EE Application improving performance.

Here is a little anti-pattern -- that depending on your application -- could be costing you.

While learning up on my legacy J2EE app. I noticed a lot of:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String dateString = sdf.format(someDate);
and/or
Date date = sdf.parse(someString);

since these statements were inside the execute method of a Struts action, each HttpRequest was creating an instance of SimpleDateFormat -- and shortly thereafter discarding it..

Now SimpleDateFormat.parse() is not threadSafe.. so this is not all bad if you ARE parsing -- however, nine times out of ten, you will be just formatting. in which case you should create the SimpleDateFormat as an instance variable like so:

private static final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

If you already have apache-commons in your project, use FastDateFormat -- like so:

private static final FastDateFormat basicDateFormat = FastDateFormat.getInstance( "MM/dd/yyyy", Locale.US );

Now this leads to an important question. If you are not already using apache-commons -- should you?

Not for just this one option. In my opinion, unless a) you intend to use more than a few functions b) everyone in your project is familiar and willing to use them and most important c) someone takes ownership of maintaining this 'third party library'. i.e. resolving issues, downloading fixes, updates as and when necessary etc.

And, keep in mind that you WILL be introducing a dependency -- so if and when you migrate your appserver say from one that uses Java 1.5 to Java 1.6, it will be one more thing to check and confirm and perhaps upgrade and test. So, though it is easy enough to download and throw this library into WEB-INF/lib, there is an ongoing cost to use it -- make sure it is worth it.

No comments:

Post a Comment