SimpleDateFormat in web technology


Many of times we are using java SimpleDateFormat class to format the date and convert the date into String and vice verse.

Sometimes, by mistake we are creating a static instance of the SimpleDateFormat object, as either it is used in many of other classes or used many times in same class. This is the example of the same

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

And we put this in some constant class and as and when required, we use this with the static reference.

This will work perfectly fine, but other part is that the SimpleDateFormat is not synchronized. So, let say, if we are working in Struts (Action classes) or say some Portlets (Portlet classes) and we make use of this static reference, then chances are higher that we get false values for the dates.

While converting and formatting dates, SimpleDateFormat stores the provided date value into its instance variable and start the converting process.

Since we have made it as a static reference, 2 web request running on different threads may access this at a same time and we get stale data.

Hope this will help!

keep coding!

No comments:

Post a Comment