Some thoughts and summary of ThreadLocal

I read some ThreadLocal related analysis articles, and summarized the following information. If there is any error, please correct me and study together:

  1. 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.
  2. 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.
  3. 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.
  4. ThreadLocal does not solve the problem of thread safety, that is, the problem of dirty reads still exists.
  5. 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.
  6. In other words, ThreadLocal realizes data isolation, that is, each thread uses independent data of each thread.
  7. ThreadLocal is not used for data sharing.

Guess you like

Origin blog.csdn.net/u013821237/article/details/89925626