ThreadLocal Translated into Chinese, the more accurate name should be : Thread local variables .

   What's the use of this thing , Or why is there such a thing ? Explain it first , In concurrent programming , If the member variable does not do any processing, it is actually thread unsafe , Each thread is operating on the same variable , Obviously not , And we know that volatile This keyword is not thread safe . Well, in one case , We need to meet such a condition : Variables are the same , But each thread uses the same initial value , That is, a new copy of the same variable is used . In this case ThreadLocal It's very useful , for instance DAO Database connection for , We know DAO It's a singleton , So his attributes Connection It's not a thread safe variable . And we need it for every thread , And each uses its own . This situation ,ThreadLocal This is a better solution to this problem .

   We analyze this problem from the perspective of source code .

   First define a ThreadLocal:
public final class ConnectionUtil { private ConnectionUtil() {} private static
final ThreadLocal<Connection> conn = new ThreadLocal<>(); public static
Connection getConn() { Connection con= conn.get(); if (con == null) { try {
Class.forName("com.mysql.jdbc.Driver"); con =
DriverManager.getConnection("url", "userName", "password"); conn.set(con); }
catch (ClassNotFoundException | SQLException e) { // ... } } return con; } }
 

   this look , They all use the same connection , But every connection is new , Is a copy of the same connection .

   What is the implementation mechanism ?

  1, each Thread Objects maintain a ThreadLocalMap Such a one ThreadLocal Of Map, Can store several ThreadLocal.
/* ThreadLocal values pertaining to this thread. This map is maintained * by
the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null;

  2, When we call get() Methods , Get current thread first , Then get the current thread's ThreadLocalMap object , If not empty , Then take it out ThreadLocal Of value, Otherwise, initialize it , Initialization means that initialValue Value of set reach ThreadLocal in .
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map =
getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if
(e != null) return (T)e.value; } return setInitialValue(); }
  3, When we call set() Methods , It's routine , Is to set the value into the ThreadLocal in .

  4, summary : When we call get Methods , In fact, there is one in each current thread ThreadLocal. Each time you get or set the ThreadLocal Operations performed , Is separate from other threads .

  5, Application scenarios : When many threads need to use the same object more than once , And it is best used when the object has the same initialization value ThreadLocal.

  6, In fact, it is better to see the source code more clearly . If you want to see the source code , It involves one WeakReference And a Map, These two places need to be understood , These two things are a.Java Weak reference of , that is GC The reference package will be destroyed ( quote ) Object of , this threadLocal As key Could be destroyed , But as long as we define it as his class, it doesn't unload ,tl This strong reference always refers to this ThreadLocal Of , Never be gc fall .b. and HashMap almost .

   in fact , In essence , Each thread maintains one map, And this one map Of key namely threadLocal, And value is us set The value of , Every time the thread is in get When , Take values from their own variables , Since we take values from our own variables , There must be no thread safety problem , On the whole ,ThreadLocal The state of this variable has not changed at all , He was just acting as a key The role of , In addition, each thread is provided with an initial value . If you will , We can do this on our own , It just happened JDK He's already done this for us .

Technology
©2019-2020 Toolsou All rights reserved,
C Review of basic language knowledge Go Language learning notes (GUI programming )Java Misunderstanding —— Method overloading is a manifestation of polymorphism ? How to achieve low cost and high stability for cloud native applications ?elementui Shuttle box el-transfer Display list content text too long C/C++ Memory model Element-Ui assembly Message Message prompt , alert Popup C# Making a simplified version of calculator Python In pycharm editor Interface style modification Tiktok refresh progress bar ( Two little balls turn ), The code is simple