Is SimpleDateFormat thread safe?
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 {
private static ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>() {
@Override protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("YYYY-MM-dd");
}
};
public static void main(String[] args) throws ParseException {
System.out.println(formatter.get().parse("2020-11-04").getTime());
}
}