Date Conversion with ThreadLocal

后端 未结 2 1453
无人及你
无人及你 2021-01-05 00:44

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 th

2条回答
  •  萌比男神i
    2021-01-05 01:49

    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 format1 = new ThreadLocal() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    
    public String formatDate(Date date) {
        return format1.get().format(date);
    }
    

提交回复
热议问题