Ahmad.Masood Ahmad.Masood - 3 months ago 15
Java Question

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));
}

Answer

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

Comments