Is Java’s SimpleDateFormat class thread-safe?

  1. Accepted Answer

Accepted Answer

No, the SimpleDateFormat class is not thread-safe. If you want to share an instance of it between threads, you must synchronize access within each thread.

A better alternative is the DateTimeFormatter class. It was introduced in Java 8. It’s also used for printing and parsing dates in Java, and it is thread-safe and immutable. You can use it without additional synchronization or worrying about thread-safety.

In short, SimpleDateFormat is not thread-safe and you must use proper synchronization. If you can, avoid using SimpleDateFormat and use DateTimeFormatter class instead. Here’s an example using DateTimeFormatter:

LocalDate localDate = LocalDate.now();
	
DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss");
String date = dtFormatter.format(localDate); //2021-Oct-10

Speak Your Mind