Data Corruption issue running function in Tomcat 5.5 & 6.0
I've been trying to figure out this bug for few days. I have narrowed the issue down to a test case as follows. Again, this is a test case that causes the bug to happen. The function (at this point) is not a practical one, but just trying to figure out the bug.
Server is running: - Tomcat 6 - OpenJDK 1.6.0_17 - CentOS 5.5
I have a simple Class file with the following method Static Method and Static variable declaration:
public static java.text.SimpleDateFormat displayDateSDF1 = new java.text.SimpleDateFormat("MM/dd/yyyy");
public static java.util.Date getSubDateMini(String inputDate)
{
java.util.Date testObj = null;
try
{
testObj = displayDateSDF1.parse("01/01/2000") ;
}
catch (Exception e)
{
}
return testObj;
}
Testing in Tomcat:
When I run this method, I'd expect to get the same result every time, right? However, if I call this method from a JSP, I get the expected result of a Date object with value 1/1/2000 about 99.9% of the time. However, sometimes I get an unexpected data object passed back 开发者_如何转开发with a seemingly random date value.
To test this, I created a JSP with the following code segment in it:
for (int i=0; i<200000;i++)
{
java.util.Date testObjLib = TestDate.getSubDateMini("") ;
if (testObjLib!=null&&!testObjLib.toString().equalsIgnoreCase("Sat Jan 01 00:00:00 PST 2000"))
{
out.print("<br>"+testObjLib+"");
}
}
Some dates that appear are as follows:
Wed Jan 01 00:00:00 PST 1
Fri Aug 01 00:00:00 PDT 2166
In 200,000 runs, I get approximately 50 bad dates which gives an error rate of ~0.025% but again it's random. I've run this loop with 10 iterations and received an error. Sometimes it runs the loop with 200,000 and all dates look good.
Testing in Java:
Running this loop via a console/terminal app in CentOS with the same loop, I have not seen this error happen yet. I increased the loop to 10,000,000 and had no false results as of yet.
I can understand out of memory or some thrown error (which would result in a null value) but not corrupt/inconsistent data. I built up a new server from scratch with Tomcat 6 and also tried Tomcat 5.5 and both have the same results. I have not tried Tomcat 7.
Any suggestions?
SimpleDateFormat
is not thread-safe.
This means that when it is accessed from multiple threads, unexpected results can be observed. And tomcat is serving each request from a separate thread, so whenever two requests are made at the same time, the problem would arise.
You have a number of options:
- instantiate the
SimpleDateFormat
on each call of the method (rather than making itstatic
) - if you need the format more than once per thread, use a
ThreadLocal
to store it. - alternatively use joda-time, where
DateTimeFormat
is thread-safe.
精彩评论