Synchronizing access to SimpleDateFormat

前端 未结 9 1440
名媛妹妹
名媛妹妹 2020-12-02 06:56

The javadoc for SimpleDateFormat states that SimpleDateFormat is not synchronized.

\"Date formats are not synchronized. It is recommended to create

相关标签:
9条回答
  • 2020-12-02 07:23

    If you are using Java 8, you may want to use java.time.format.DateTimeFormatter:

    This class is immutable and thread-safe.

    e.g.:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String str = new java.util.Date().toInstant()
                                     .atZone(ZoneId.systemDefault())
                                     .format(formatter);
    
    0 讨论(0)
  • 2020-12-02 07:23

    Imagine your application has one thread. Why would you synchronize access to SimpleDataFormat variable then?

    0 讨论(0)
  • 2020-12-02 07:25

    Another option is to keep instances in a thread-safe queue:

    import java.util.concurrent.ArrayBlockingQueue;
    private static final int DATE_FORMAT_QUEUE_LEN = 4;
    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private ArrayBlockingQueue<SimpleDateFormat> dateFormatQueue = new ArrayBlockingQueue<SimpleDateFormat>(DATE_FORMAT_QUEUE_LEN);
    // thread-safe date time formatting
    public String format(Date date) {
        SimpleDateFormat fmt = dateFormatQueue.poll();
        if (fmt == null) {
            fmt = new SimpleDateFormat(DATE_PATTERN);
        }
        String text = fmt.format(date);
        dateFormatQueue.offer(fmt);
        return text;
    }
    public Date parse(String text) throws ParseException {
        SimpleDateFormat fmt = dateFormatQueue.poll();
        if (fmt == null) {
            fmt = new SimpleDateFormat(DATE_PATTERN);
        }
        Date date = null;
        try {
            date = fmt.parse(text);
        } finally {
            dateFormatQueue.offer(fmt);
        }
        return date;
    }
    

    The size of dateFormatQueue should be something close to the estimated number of threads which can routinely call this function at the same time. In the worst case where more threads than this number do actually use all the instances concurrently, some SimpleDateFormat instances will be created which cannot be returned to dateFormatQueue because it is full. This will not generate an error, it will just incur the penalty of creating some SimpleDateFormat which are used only once.

    0 讨论(0)
提交回复
热议问题