java.text.SimpleDateFormat not thread safe

后端 未结 3 947
刺人心
刺人心 2020-12-31 15:39
Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concur         


        
3条回答
  •  灰色年华
    2020-12-31 16:12

    That's true. You can find already questions concerning this issue on StackOverflow. I use to declare it as ThreadLocal:

    private static final ThreadLocal THREAD_LOCAL_DATEFORMAT = new ThreadLocal() {
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
    };
    

    and in the code:

    DateFormat df = THREAD_LOCAL_DATEFORMAT.get();
    

提交回复
热议问题