SimpleDateFormat is not ThreadSafe

SimpleDateFormat is not ThreadSafe

Problems with SimpleDateFormat

Recently, I needed to be generated one csv with until 50k rows. One these fields was a date. Optimizing the iteration in collection:

myBigList.parallelStream(...)

In the middle of setters was one SimpleDateFormat and NumberFormatException and errors of multiple lines was shown. So, I remember: SimpleDateFormat is not thread safe. In this case, to solve this, just use DateTimeFormatter, that is thread safe. The difference is that DateTimeFormatter work with LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("myPattern");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

and that’s all folks!

If you have any doubts, problems or suggestions, just leave a message.