Date Conversion with ThreadLocal

user2680017 picture user2680017 · Sep 3, 2013 · Viewed 12.6k times · Source

I have a requirement to convert incoming date string format "20130212" (YYYYMMDD) to 12/02/2013 (DD/MM/YYYY)

using ThreadLocal. I know a way to do this without the ThreadLocal. Can anyone help me?

Conversion without ThreadLocal:

    final SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
    final SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
    final Date date = format1.parse(tradeDate);
    final Date formattedDate = format2.parse(format2.format(date));

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Sep 3, 2013

The idea behind this is that SimpleDateFormat is not thread-safe so in a mutil-threaded app you cannot share an instance of SimpleDateFormat between multiple threads. But since creation of SimpleDateFormat is an expensive operation we can use a ThreadLocal as workaround

static ThreadLocal<SimpleDateFormat> format1 = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("yyyy-MM-dd");
    }
};

public String formatDate(Date date) {
    return format1.get().format(date);
}