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

1274

被折叠的 条评论
为什么被折叠?



