時間轉換封裝 線程安全

爲了有一個公用的時間處理工具,就封裝了一個,該封裝的工具是線程安全的,可以放心使用。

public class SafeDateFormat {

    final static Map<String, ThreadLocal<DateFormat>> threadLocalPool = new HashMap<>();
    final static ThreadLocal<DateFormat> DefaultThreadLocal = new ThreadLocal<DateFormat>() {
        @Override
        protected synchronized DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    static {
        threadLocalPool.put("yyyy-MM-dd HH:mm:ss", DefaultThreadLocal);
    }

    public static Date parse(String dateStr) throws ParseException {

        return DefaultThreadLocal.get().parse(dateStr);

    }

    public static Date parse(final String format, String dateStr) throws ParseException {
        ThreadLocal<DateFormat> threadLocal = threadLocalPool.get(format);
        if (threadLocal == null) {
            threadLocal = new ThreadLocal<DateFormat>() {
                @Override
                protected synchronized DateFormat initialValue() {
                    return new SimpleDateFormat(format);
                }
            };
            threadLocalPool.put(format, threadLocal);
        }
        return threadLocal.get().parse(dateStr);

    }

    public static String format(Date date) {
        return DefaultThreadLocal.get().format(date);
    }

    public static String format(final String format, Date date) {
        ThreadLocal<DateFormat> threadLocal = threadLocalPool.get(format);
        if (threadLocal == null) {
            threadLocal = new ThreadLocal<DateFormat>() {
                @Override
                protected synchronized DateFormat initialValue() {
                    return new SimpleDateFormat(format);
                }
            };
            threadLocalPool.put(format, threadLocal);
        }
        return threadLocal.get().format(date);
    }


發佈了75 篇原創文章 · 獲贊 8 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章