Main Contents

Bug in Java 1.5 Timestamp.compareTo()

test driven development, software development

About two months ago we caught a nasty issue with getting some ClassCastExceptions when comparing two Dates. The code that failed the unit tests looked something like:

if (startDate.compareTo(endDate) < 0) {

The strange part was the developers running IBM’s RAD 6.0 never had failing tests and ClassCastExceptions. The tests failed on the build box. When I tried the tests in IntelliJ they failed as well. After some investigation it was apparent it some of the Dates were coming from a Hibernate mapping class and so they were dates, but in actuality they were java.sql.Timestamps. Since TimeStamp extends java.util.Date this wouldn’t appear to be much of an issue. The fix was simple enough:

startDate is actually a java.sql.Timestamp
endDate is actually just a java.util.Date

So just switching the order and utilizing java.util.Date's compareTo() makes the problem go away.

if (endDate.compareTo(startDate) > 0) {

Seemed like a crappy overriding of the compareTo() method by java.sql.Timestamp, but it did fix the problem. Some more digging turned up the real story. A bug, #6304469, was actually introduced in Java 1.5 and has now been fixed in 1.6. Since RAD 6.0 was running in 1.4 and it only supports 1.4 this explained why we didn’t see the bug in RAD.

The explanation in the Java 1.6 release notes is:

A regression introduced in J2SE 5.0 created a binary compatibility problem with java.sql.Timestamp.compareTo which was only detectable at run-time.
This bug is fixed in Java SE 6, Beta2 and in J2SE 5.0, Update 7 (5.0u7).

Ed Gibbs @ December 9, 2006

Leave a comment


Feed