使用ThreadLocal或DateFormatUtils解决SimpleDateFormat线程安全问题

1.使用ThreadLocal,令每个线程创建一个当前线程的SimpleDateFormat的实例对象。

例:

SuffixNameUtil.java 获取时间戳后缀名Util
package com.bj58.bic.pan.scf.utils;

import org.apache.commons.collections.MapUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 获取后缀名工具类
 * create by mulin on 2019.09.02
 */
public class SuffixNameUtil {

    private static final Logger logger = LogManager.getLogger(DocAndDirManagerImpl.class);
    private static final String DATE_FORMAT = "_yyyyMMdd_HHmmss";

    private static ThreadLocal> threadLocal = new ThreadLocal>(){
        protected synchronized HashMap initialValue() {
            logger.info("SimpleDateFormatThreadLocal initialValue -- ");
            return new HashMap<>();
        }
    };

    /**
     * 获取后缀名
     * @return _年月日_时分秒_一位随机数
     */
    public static String getSuffixName() {

        Map dateMap = threadLocal.get();
        SimpleDateFormat sdf = dateMap.get(DATE_FORMAT);
        if (MapUtils.isEmpty(dateMap)) {
            logger.info("getSuffixName SimpleDateFormatThreadLocal initialValue -- ");
            sdf = new SimpleDateFormat(DATE_FORMAT);
            dateMap.put(DATE_FORMAT, sdf);
            threadLocal.set(dateMap);
        }

        Random random = new Random();
        int ends = random.nextInt(10);

        return sdf.format(new Date()) + "_" + ends;
    }
}

 

2.Apache的 DateFormatUtils 与 FastDateFormat

使用org.apache.commons.lang.time.FastDateFormat 与 org.apache.commons.lang.time.DateFormatUtils。

例:

import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.Date;
import java.util.Random;

/**
 * 获取后缀名工具类
 * create by mulin on 2019.09.02
 */
public class SuffixNameUtil {

    private static final String DATE_FORMAT = "_yyyyMMdd_HHmmss";

    /**
     * 获取后缀名
     * @return _年月日_时分秒_一位随机数
     */
    public static String getSuffixName() {
        String format = DateFormatUtils.format(new Date(), DATE_FORMAT);

        Random random = new Random();
        int ends = random.nextInt(10);

        return format + "_" + ends;
    }
}

 

你可能感兴趣的:(线程安全,DateFormatUtils)