SimpleDateFormat is not thread-safe, and should not be used as a constant field.


The problem

SimpleDateFormat is not thread-safe. The documentation recommendeds creating separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

The Google Java Style Guide ยง5.2.4 requires CONSTANT_CASE to only be used for static final fields whose contents are deeply immutable and whose methods have no detectable side effects, so fields of type SimpleDateFormat should not use CONSTANT_CASE.

TIP: Consider using the java.time API added in Java8, in particular DateTimeFormatter. One its many advantages over SimpleDateFormat is that it is immutable and thread-safe.

If the date formatter is accessed by multiple threads, consider using ThreadLocal:

private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
    ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm"));

If the field is never accessed by multiple threads, rename it to use lowerCamelCase.

private static final SimpleDateFormat dateFormat =
    new SimpleDateFormat("yyyy-MM-dd HH:mm");


Suppress false positives by adding an @SuppressWarnings("SimpleDateFormatConstant") annotation to the enclosing element.