Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making DateFormat Threadsafe. What to use, synchronized or Thread local

I want to make following code thread safe. What is the best way to achieve it?

private static final DateFormat DATE_FORMAT = DateFormat.getDateTimeInstance();

public static final String eventTypeToDateTimeString(long timestamp)
{
   return DATE_FORMAT.format(new Date(timestamp));
}
like image 774
Ahmad.Masood Avatar asked Apr 06 '15 18:04

Ahmad.Masood


1 Answers

You can

  1. Create a new DateFormat instance every time you need one.

  2. Use a synchronized block, as pointed by @Giovanni Botta.

  3. Use ThreadLocal:

    private static final ThreadLocal<DateFormat> THREADLOCAL_FORMAT =
        new ThreadLocal<DateFormat>() {
            @Override protected DateFormat initialValue() {
                return DateFormat.getDateTimeInstance();
            }
        };
    
    public static final String eventTypeToDateTimeString(long timestamp) {
        return THREADLOCAL_FORMAT.get().format(new Date(timestamp));
    }
    

Actually, using ThreadLocal might give you the best performance if you have a thread pool (meaning threads are reused), which most web containers do.

Reference

http://www.javacodegeeks.com/2010/07/java-best-practices-dateformat-in.html

like image 105
ericbn Avatar answered Oct 06 '22 10:10

ericbn