如何优雅地处理日期格式化类SimpleDateFormat存在的线程安全问题

SimpleDateFormat是线程不安全的类,一般不建议定义为static变量,因为在多线程操作时会出现线程不安全问题,进而导致相关的问题

解决方案:

使用ThreadLocal进行操作

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

/**
 * 考虑到SimpleDateFormat为线程不安全对象,故应用ThreadLocal来解决,
 * 使SimpleDateFormat从独享变量变成单个线程变量
 */
public class DateFormatUtils {

    //写法1:
    private static ThreadLocal<SimpleDateFormat> threadLocal1 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    public static Date parseByOne(String dateStr) throws ParseException {
        return threadLocal1.get().parse(dateStr);
    }

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


    //写法2:
    private static final String date_format = "yyyy-MM-dd HH:mm:ss";
    private static ThreadLocal<SimpleDateFormat> threadLocal2 = new ThreadLocal<SimpleDateFormat>();
    public static SimpleDateFormat getDateFormat() {
        SimpleDateFormat sdf = threadLocal2.get();
        if (sdf == null) {
            sdf = new SimpleDateFormat(date_format);
            threadLocal2.set(sdf);
        }
        return sdf;
    }

    public static String formatDate(Date date) throws ParseException {
        return getDateFormat().format(date);
    }

    public static Date parseByTwo(String strDate) throws ParseException {
        return getDateFormat().parse(strDate);
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值