The relationship between ThreadLocal and volatile

for unprotected multithreads, it is uncertain when some data is modified in one thread and when it is submitted to main memory, and the values used by other threads are not necessarily up-to-date.
in the case of volatile modification, it is guaranteed to be submitted to main memory immediately after modification.
can ThreadLocal be simply understood to mean that variables in working memory of each thread are never submitted to main memory

Mar.06,2021

do two things that don't matter. You can also put the volatile variable in ThreadLocal, but ThreadLocal is only used by the current thread in principle, so there is no need to do so.
if you have any other specific requirements, put the code up and take a look.


ThreadLocal is currently visible to threads, and there is no problem of communication between threads.

Volatile, on the other hand, can ensure visibility while sharing variables between threads, so that threads can cooperate successfully.

there is a big difference between the two application scenarios.


to put it simply, volatile ensures that threads always see the latest values. Threadlocal is one for each thread, and the two are not related at all.

Menu