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.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e3dc5b-4be6a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e3dc5b-4be6a.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?