java.text.SimpleDateFormat not thread safe

后端 未结 3 919
刺人心
刺人心 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 15:53

    Thats correct. FastDateFormat from Apache Commons Lang is a nice threadsafe alternative.

    Since version 3.2 it supports also parsing, before 3.2 only formatting.

    0 讨论(0)
  • 2020-12-31 16:03

    Yes SimpleDateFormat is not thread safe and it is also recommended when you are parsing date it should access in synchronized manner.

    public Date convertStringToDate(String dateString) throws ParseException {
        Date result;
        synchronized(df) {
            result = df.parse(dateString);
        }
        return result;
    }
    

    one other way is on http://code.google.com/p/safe-simple-date-format/downloads/list

    0 讨论(0)
  • 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<DateFormat> THREAD_LOCAL_DATEFORMAT = new ThreadLocal<DateFormat>() {
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyyMMdd");
        }
    };
    

    and in the code:

    DateFormat df = THREAD_LOCAL_DATEFORMAT.get();
    
    0 讨论(0)
提交回复
热议问题