I read some ThreadLocal related analysis articles, and summarized the following information. If there is any error, please correct me and study together:
- The implementation before jdk1.3 is different. It maintains a Map in ThreadLocal, with Thread as the key and variables as the value. However, such multi-threaded concurrent access needs to be synchronized, so the speed is relatively slow.
- Later, each Thread holds a ThreadLocalMap variable, so there will be no synchronization problems with the passed in variables , because each Thread stores a reference, which has become an evolved function of ThreadLocal.
- In ThreadLocalMap, ThreadLocal is used as the key, and the object passed in is used as the value. At this time , the object reference is passed in instead of a new object coming in. That is to say, other threads modify the value of this object, and other threads Values also correspond to changes , except for basic data types, because they are not reference types.
- ThreadLocal does not solve the problem of thread safety, that is, the problem of dirty reads still exists.
- Therefore, the main function of ThreadLocal is to simplify the transfer of parameters to the thread . Otherwise, in addition to defining the variable as static and globally available, it will not be convenient for all threads to access it, not to solve the thread safety problem.
- In other words, ThreadLocal realizes data isolation, that is, each thread uses independent data of each thread.
- ThreadLocal is not used for data sharing.