The goal ThreadLocalis that fields do not have to be atomic - there is no need to synchronize their values โโwith centralized memory. They are local to the stream and exist only in the local data store of the streams.
Why would I like to use ThreadLocal instead of, say, AtomicLong or AtomicInteger?
ThreadLocalvery useful for storing copies for each thread. For example, SimpleDateFormatwhich, unfortunately, is not reentrant.
private final ThreadLocal<DateFormat> threadLocal =
new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
}
};
...
DateFormat dateFormat = threadLocal.get();
This is a useful template, because then we donโt need synchronizeto or worry about any volatileor other atomic operations on it that have memory barriers.
source
share