All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.jfunc.common.datetime.DatetimeUtil Maven / Gradle / Ivy

There is a newer version: 1.8.5
Show newest version
package top.jfunc.common.datetime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取线程安全的SimpleDateFormat的Date工具类,根据pattern缓存ThreadLocal
 * @author 熊诗言 2017/12/29
 */
public class DatetimeUtil {
    private static final Logger logger = LoggerFactory.getLogger(DatetimeUtil.class);

    /** 锁对象 */
    private static final Object LOCK_OBJ = new Object();

    /** 存放不同的日期模板格式的sdf的Map */
    private static Map> sdfMap = new HashMap<>();

    /**
     * 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
     * @param pattern 日期格式字符串 ,例如yyyy-MM-dd HH:mm:ss
     * @return 线程安全的SimpleDateFormat
     */
    private static SimpleDateFormat getSdf(final String pattern) {
        ThreadLocal tl = sdfMap.get(pattern);

        // 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf
        if (tl == null) {
            synchronized (LOCK_OBJ) {
                tl = sdfMap.get(pattern);
                if (tl == null) {
                    // 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map
                    logger.trace("put new sdf of pattern " + pattern + " to map");
                    // 这里是关键,使用ThreadLocal替代原来直接new SimpleDateFormat
                    tl = ThreadLocal.withInitial(()->new SimpleDateFormat(pattern));
                    sdfMap.put(pattern, tl);
                }
            }
        }

        return tl.get();
    }

    /**
     * 是用ThreadLocal来获取SimpleDateFormat,这样每个线程只会有一个SimpleDateFormat
     * 
     * @param date 日期
     * @param pattern 格式字符串
     */
    public static String format(Date date, String pattern) {
        return getSdf(pattern).format(date);
    }

    public static Date parse(String dateStr, String pattern) throws ParseException {
        return getSdf(pattern).parse(dateStr);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy