Data type conversion is one of the most common task in programming and a good programmer must know how to convert one type to other type. There are many times, when you will be required to convert a String to java.util.Date object mostly in different format e.g.
dd-MM-yy or
yyyy-MM-dd or simply
yyyy MM dd. For example, client pass dates as String to Server or sometime we read Date related data from CSV file. Java provides API for
parsing String to date using DateFormat class, though Java's Date and Time API is severely criticized, it is also the most used Date and Time format solution. Though Joda Date and Time API is always there and now Java 8 also got new date and time API, many of us don't have luxury to use it in production. Many enterprise application is still running on Java 5 and Java 6, forget about JDK 7 or 8. It may take another 5 year before you start using
lambda expressions and
Stream API. Apart from several design mistake of
Date class e.g. mutability, not intuitive, most obvious problem with formatting date in Java is
SimpleDateFormat not being thread-safe. That's why I wrote this post to show how to convert String to Date correctly in Java multi-threading environment. There are mainly two ways to use
SimpleDateFormat properly in concurrent application, either synchronize the access to
DateFormat object or use
ThreadLocal variable. Earlier we have see
how to make SimpleDateFormat thread-safe, and in this tutorial, we will learn how to use synchronized keyword for making
DateFormat thread-safe.