Using ThreadLocal vs Atomic

According to ThreadLocaljavadoc, it sounds like its specific stream for 1 + atomic fields.

Is it a goal to ThreadLocalrepresent all atomic fields for one Thread, or is it just a convenience container provided when you have multiple instances Atomic*that should be logically grouped together?

I think I wonder why I will ever want to use ThreadLocalinstead of, say, AtomicLongor AtomicInteger? Thanks in advance!

+3
source share
2 answers

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");
    }
};
...
// get one that is per-thread
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.

+8
source

I think I'm wondering why would I ever want to use ThreadLocal instead of, say, AtomicLong or AtomicInteger?

. ThreadLocal , , . , , ThreadLocal, .

Atomic* , , .

+1

All Articles