Is SimpleDateFormat thread safe?
Published
Updated
Java’s SimpleDateFormat is not thread safe. It can easily be made thread safe by enclosing it within a ThreadLocal construct.
For example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ThreadLocalExample {
public static ThreadLocal<SimpleDateFormat> formatter =
ThreadLocal.withInitial(() -> new SimpleDateFormat("YYYY-MM-dd"));
public static void main(String[] args) throws ParseException {
System.out.println(formatter.get().parse("2020-11-04").getTime());
}
}