ThreadLocal类与SimpleDateFormat类

本文探讨了ThreadLocal类如何确保线程封闭性,防止对可变单例或全局变量的共享,以实现线程安全。通过具体示例说明了SimpleDateFormat类的线程不安全性,并提出了解决方案,即利用ThreadLocal来创建线程局部变量,确保在多线程环境下SimpleDateFormat的正确使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ThreadLocal类维持线程封闭性,可以使线程中的某个值与保存值得对象关联起来。为每个使用该变量的线程都存有一份独立的脚本,因此get总是返回当前执行线程在调用set时设置的最新值。

ThreadLocal对象通常用于防止对可变的单实例变量(Singleton)或全局变量进行共享(在多线程应用程序在没有协同的情况下使用全局变量时,就不是线程安全的)

深入理解Java:SimpleDateFormat安全的时间格式化

SimpleDateFormat的线程安全问题与解决方案

SimpleDateFormat类的非线程安全:

public class MTAuth {

    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    // SimpleDateFormat 这个是非线程安全的
    private static SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
    public static String getAuthDate(Date date) {

        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        String dateString = df.format(date);

        return dateString;

    }
}

线程安全:

public class DwUtil {
    private static final Logger LOG = LoggerFactory.getLogger(DwUtil.class.getName());
    private static ThreadLocal<SimpleDateFormat> local1 = new ThreadLocal<SimpleDateFormat>();
    private static ThreadLocal<SimpleDateFormat> local2 = new ThreadLocal<SimpleDateFormat>();

    public static Date parseDate(String str, boolean lenient) {
        SimpleDateFormat sdf = local1.get();
        if (sdf == null) {
            sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
            local1.set(sdf);
        }

        try {
            sdf.setLenient(lenient);
            return sdf.parse(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static String formatDate(Date date) {
        SimpleDateFormat sdf = local1.get();
        if (sdf == null) {
            sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
            local1.set(sdf);
        }

        return sdf.format(date);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值