Java Concurrency--Detailed Explanation of ThreadLocal

Article Directory

What is ThreadLocal?

ThreadLocalIt is called a thread local variable , ThreadLocaland the variable filled in belongs to the current thread, and the variable is isolated from other threads. ThreadLocalA copy of the variable is created in each thread , so each thread can access its own internal copy variable.

The use of ThreadLocal

  1. When objects are transferred across layers, use ThreadLocalcan avoid multi-layer transfer and break the constraints between layers.
  2. Data isolation between threads.
  3. Perform transaction operations to store thread transaction information.
  4. Database connection, Session session management.

How to use ThreadLocal

ThreadLocalThe role of each thread is to create a copy.

Insert picture description here


As can be seen from the above examples, each thread has its own localvalue, and setting a sleep time is for another thread to read the current localvalue in time.

Use when connecting to the database

Insert picture description here


The above is a database connection management class . When using a database, first establish a database connection, and then close it after use. There is a problem here: if a client frequently uses the database, it needs to establish multiple connections and closes In this way, the server may be overwhelmed. If there are 10,000 clients, the pressure on the server will be even greater.
It can be used at this time ThreadLocal, it will create a copy of the connection in each thread, and it can be used anywhere within the thread, and the threads do not affect each other, so that there is no thread safety problem, and it will not be serious Affect program execution performance.

How ThreadLocal works

ThreadLocalThe main methods in:

Insert picture description here

set method

Insert picture description here


First get the current thread t, and then call getMapget ThreadLocalMap. If the map exists, the current thread object is used as the key, and the object to be stored is stored in the map as the value. If the map does not exist, one is initialized.
ThreadLocalMap:

Insert picture description here

ThreadLocalMapIt is ThreadLocala static inner class, which defines one Entryto store data, and it is also an inherited weak reference. It Entryis used internally ThreadLocalas the key, and the value we set is used as the value.
getMapmethod:

ThreadLocalMap getMap(Thread t) {

   return t.threadLocals;

}

Call the current thread t, return the member variables in the current thread t threadLocals, threadLocalsthat's it ThreadLocalMap.

get() method

Insert picture description here


First get the current thread, and then call the getMapmethod to get a ThreadLocalMap, if the map is not null, then use the current thread as ThreadLocalMapthe Entrykey, then the corresponding value is a value, if not set an initial value.
Set the initial value:

Insert picture description here

remove() method

Insert picture description here

From mapremove it in.

summary

  1. Each Thread maintains a ThreadLocalMapreference internally
  2. ThreadLocalMapYes ThreadLocalinternal class, use Entry to store
  3. ThreadLocalThe created copy is stored in your own threadLocals, which is your ownThreadLocalMap
  4. ThreadLocalMapThe key value is an ThreadLocalobject, and there can be multiple threadLocalsvariables, so it is stored in the map.
  5. Before doing get, you must first set, otherwise a null pointer exception will be reported. Of course, one can also be initialized, but the initialValue()method must be rewritten .
  6. ThreadLocalIt does not store the value itself, it just serves as a key to allow the thread to ThreadLocalMapobtain the value.

be careful

Insert picture description here
  1. There is a map in Thread, which isThreadLocalMap
  2. ThreadLocalMapThe key is ThreadLocal, the value is set by ourselves.
  3. ThreadLocalIt is a weak reference. When it is null, it will be treated as garbage.
  4. If our ThreadLocal is null, it will be recycled by the garbage collector, but at this time, our ThreadLocalMap has the same life cycle as Thread, and it will not be recycled. At this time, there will be a phenomenon, that is, the key of ThreadLocalMap is gone, but The value is still there, which causes a memory leak. Solution: After using ThreadLocal, perform the remove operation to avoid memory overflow.