Video in progress
Why does a `static final SimpleDateFormat` field give strange dates on prod, and what design lesson comes out of it?
SimpleDateFormat has mutable state inside (a Calendar) and is not thread-safe. If one static instance is used by many threads, the results get mixed up or you get a NumberFormatException. The fix is the immutable, thread-safe DateTimeFormatter. The lesson: a shared object must be immutable.
📖 Answer
public class ReportUtil {
private static final SimpleDateFormat FMT = new SimpleDateFormat("yyyy-MM-dd");
public static Date parse(String s) throws ParseException {
return FMT.parse(s); // several threads at once: the state gets corrupted
}
}
It never shows up in a local test. On prod, under load, one request's date gets mixed with another's, or parse throws a random exception. Worst of all, the error can stay silent and a wrong date gets written to the database.
The cause: during format/parse, SimpleDateFormat modifies its internal Calendar field. The field being final doesn't guarantee that the object's insides don't change.
The fix:
private static final DateTimeFormatter FMT = DateTimeFormatter.ISO_LOCAL_DATE;
public static LocalDate parse(String s) { return LocalDate.parse(s, FMT); }
DateTimeFormatter is immutable, so you can share it freely.
The general design rule: an object shared as a static field or a Spring singleton must either be immutable or be documented as thread-safe. The same risk exists with DecimalFormat, MessageDigest, Cipher, Jackson's ObjectMapper (while it's being configured), and your own "util" classes. In old code you'll see ThreadLocal<SimpleDateFormat>: it works, but moving to java.time is the right path.
Sign up to mark studied questions and save your progress.