Video in progress
The legacy code has a static final SimpleDateFormat, and prod occasionally shows wrong dates. What's the cause, and how do you migrate from java.util.Date to java.time?
SimpleDateFormat is not thread-safe: it has a single shared Calendar inside, and parallel parse/format calls corrupt each other's state, giving a wrong date or a random NumberFormatException. DateTimeFormatter is immutable and thread-safe; I start the migration at the boundaries: JDBC, JSON, external APIs.
📖 Answer
private static final SimpleDateFormat FMT = new SimpleDateFormat("yyyy-MM-dd");
Date parse(String s) throws ParseException {
return FMT.parse(s); // two threads at the same time: a problem
}
SimpleDateFormat.parse builds the result in its internal calendar field: it clears it first, then writes the year, month and day. If two threads land in between each other, one request's year gets mixed with another's month. In tests there's one thread and everything is fine; in prod under load, once a month a "payment from 2019" shows up. That's why bugs like this live so long.
A quick patch is a ThreadLocal<SimpleDateFormat> or a new object on every call. The proper fix is java.time:
private static final DateTimeFormatter FMT = DateTimeFormatter.ISO_LOCAL_DATE; // thread-safe
LocalDate d = LocalDate.parse(s, FMT);
How I organize the migration:
| Old | New |
|---|---|
java.util.Date (a point in time) |
Instant |
java.sql.Date |
LocalDate |
java.sql.Timestamp |
Instant or OffsetDateTime (if the DB has timestamptz) |
Calendar |
ZonedDateTime |
- Boundaries. JDBC 4.2:
rs.getObject("paid_at", OffsetDateTime.class). Hibernate 6 supportsjava.timetypes on its own. Spring Boot wiresJavaTimeModuleinto Jackson automatically and writes dates as ISO text. - Bridges, in places that work with the old API:
Date.from(instant),date.toInstant(),Timestamp.from(instant). One trap:java.sql.Date.toInstant()throwsUnsupportedOperationException, so usetoLocalDate(). - The patterns aren't identical. In
DateTimeFormatter,yyyymeans "year of era", and withResolverStyle.STRICTyou needuuuu.YYYY(week-year) "pushes" December 30 into the next year in both APIs: a classic bug that shows up around New Year's Eve. - Time zone.
new Date()plusSimpleDateFormatsilently used the JVM's zone. In new code the zone is explicit:ZoneId.of("Asia/Tashkent"), or store in UTC and convert only for display.
Error Prone's JavaUtilDate check or forbidden-apis stops the old types from creeping back into new code.
Sign up to mark studied questions and save your progress.