Java -- Thread-Local Variables

本文探讨了在Java中使用SimpleDateFormat类时遇到的线程安全问题,并提供了一种解决方案,即通过ThreadLocal实现每个线程拥有独立的SimpleDateFormat实例。

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

For example, the "SimpleDateFormat" class is not thread safe. Suppose we have a static variable:

public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

If two thread execute the operation:

String dateStamp = dateFormat.format(new Date());

then the result can be garbage since the internal data structures used by the "dateFormat" can be corrupted by concurrent access. You could use synchronization, which is expensive, or you could construct a local "SimpleDateFormat" object whenever you need it, but that is also wasteful.

To construct one instance per thread, use the following code:

public static final ThreadLocal<SimpleDateFormat> dateFormat =
        ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

To access the actual formatter, call

String dateStamp = dateFormat.get().format(new Date());
The first time you call "get" in a given thread, the lambda in the constructor is called. From then on, the "get" method returns the instance belonging to the current thread.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值