Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.text.SimpleDateFormat not thread safe

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally

The above line is mentioned in the JavaDoc of SimpleDateFormat class.

Does it mean that we should not create the SimpleDateFormat objects as Static.

And If we create it as static, so wherever we are using this object we need to keep it in Synchronised Block.

like image 438
Sunny Gupta Avatar asked May 02 '12 10:05

Sunny Gupta


People also ask

Is SimpleDateFormat thread-safe *?

If multiple threads access a format concurrently, it must be synchronized externally . To make the SimpleDateFormat class thread-safe, look at the following approaches : Create a new SimpleDateFormat instance each time you need to use one. Although this is thread safe, it is the slowest possible approach.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

Is Java Util date thread-safe?

Not thread safe − java. util. Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable and does not have setter methods.


1 Answers

Yes SimpleDateFormat is not thread safe and it is also recommended when you are parsing date it should access in synchronized manner.

public Date convertStringToDate(String dateString) throws ParseException {
    Date result;
    synchronized(df) {
        result = df.parse(dateString);
    }
    return result;
}

one other way is on http://code.google.com/p/safe-simple-date-format/downloads/list

like image 105
Subhrajyoti Majumder Avatar answered Sep 19 '22 04:09

Subhrajyoti Majumder