Synchronizing access to SimpleDateFormat

前端 未结 9 1488
名媛妹妹
名媛妹妹 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: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 dateFormatQueue = new ArrayBlockingQueue(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.

提交回复
热议问题