Video in progress

Senior ☕ Core Java

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
  1. Boundaries. JDBC 4.2: rs.getObject("paid_at", OffsetDateTime.class). Hibernate 6 supports java.time types on its own. Spring Boot wires JavaTimeModule into Jackson automatically and writes dates as ISO text.
  2. Bridges, in places that work with the old API: Date.from(instant), date.toInstant(), Timestamp.from(instant). One trap: java.sql.Date.toInstant() throws UnsupportedOperationException, so use toLocalDate().
  3. The patterns aren't identical. In DateTimeFormatter, yyyy means "year of era", and with ResolverStyle.STRICT you need uuuu. YYYY (week-year) "pushes" December 30 into the next year in both APIs: a classic bug that shows up around New Year's Eve.
  4. Time zone. new Date() plus SimpleDateFormat silently 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.