An overview of the

ThreadLocal is an action class that addresses thread safety by assigning a separate thread copy to each thread, thereby solving the problem of concurrent variable access conflicts. ThreadLocal is simpler and more convenient than directly using synchronized to solve thread-safety problems, and the resulting program has higher concurrency.

A classic example: When using JDBC to manipulate A database, each thread’s Connection is placed in its own ThreadLocal. This ensures that each thread operates on the database in its own Connection, preventing thread A from closing thread B’s Connection

Differences between ThreadLocal and Synchronized

Both ThreadLocal and Synchronized are used to address multithreaded concurrent access. Synchronized is used for data sharing between threads, while ThreadLocal is used for data isolation between threads. Synchronized locks variables that can only be accessed by one thread at a time, while ThreadLocal provides a copy of variables for each thread. Each thread can only maintain the internal data of its own thread, so as to realize the isolation of threads sharing data.

ThreadLocal entry application

public class ThreadLocalTest { static ThreadLocal<String> localVar = new ThreadLocal<>(); Static void print(String STR) {system.out.println (STR + ":" + localvar.get ()); // Remove local variable localvar.remove () from local memory; } public static void main(String[] args) { Thread t1 = new Thread(()->{ localVar.set("localVar1"); print("thread1"); System.out.println("after remove : " + localVar.get()); }); Thread t2 = new Thread(()->{ localVar.set("localVar2"); print("thread2"); System.out.println("after remove : " + localVar.get()); }); t1.start(); t2.start(); }}Copy the code

The results

thread2 :localVar2
after remove : null
thread1 :localVar1
after remove : null
Copy the code

According to the results, each thread maintains its own ThreadLocal value

Implementation principle and source code analysis

ThreadLocal is essentially a thread-internal storage class that allows multiple threads to manipulate only their own internal values, thereby implementing thread data isolation

This class provides thread-local variables, with each thread having a separate copy of the variable, operated by the set and GET methods. This class is usually private, by storing thread-specific information such as user ids, transaction ids, and so on.

The source code structure is as follows:

An internal class, ThreadLocalMap, is maintained within ThreadLocal. An Entry inner class and an Entry array are maintained in ThreadLocalMap. A ThreadLocal maintains a map, where the key is the current thread and the value is the data that needs to be stored. A ThreadLocalMap object is maintained for each thread, and an array of tables is maintained for each thread. And in this array, subscripts are used to determine where the data is stored.

ThreadMap source code parsing

//Entry is the ThreadLocalMap static inner class, Static class Entry extends WeakReference<ThreadLocal<? Static class Entry extends WeakReference<ThreadLocal<? >> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<? > k, Object v) { super(k); value = v; }} //ThreadLocalMap constructor ThreadLocalMap(ThreadLocal<? > firstKey, Object firstValue) {// Internal member array, INITIAL_CAPACITY 16 constant table = new Entry[INITIAL_CAPACITY]; / / bit operations, as a result, the same as the modulus, calculate the need to store the location of the int I = firstKey. ThreadLocalHashCode & (INITIAL_CAPACITY - 1); table[i] = new Entry(firstKey, firstValue); size = 1; setThreshold(INITIAL_CAPACITY); }Copy the code

When ThreadLocalMap is instantiated, it creates an array of 16-bit entries, calculates the subscript I by hashCode and length, and then creates an Entry object, which determines the Entry’s position in the array by calculating the subscript I.

As described above, each thread has its own unique ThreadLocal, and in a ThreadLocal there is a ThreadLocalMap, so each thread has its own ThreadLocalMap. So if you declare different types of ThreadLocal in a single thread, you end up with the same ThreadLocalMap.

ThreadLocal<A> sThreadLocalA = new ThreadLocal<A>();
ThreadLocal<B> sThreadLocalB = new ThreadLocal<B>();
ThreadLocal<C> sThreadLocalC = new ThreadLocal<C>();
Copy the code

For the above multiple types of ThreadLocal, they are in the same thread, corresponding to the same ThreadLocalMap. How do they determine their position in the ThreadLocalMap Entry array?

private void set(ThreadLocal<? > key, Object value) { Entry[] tab = table; int len = tab.length; Int I = key.threadLocalHashCode & (len-1); If the key already exists, update for (Entry e = TAB [I]; e ! = null; e = tab[i = nextIndex(i, len)]) { ThreadLocal<? > k = e.get(); if (k == key) { e.value = value; return; } if (k == null) { replaceStaleEntry(key, value, i); return; TAB [I] = new Entry(key, value); TAB [I] = new Entry(key, value); Int sz = ++size; // If the array length is greater than or equal to the threshold, expand the array to twice the original size. If (! cleanSomeSlots(i, sz) && sz >= threshold) rehash(); }Copy the code
private void resize() { Entry[] oldTab = table; int oldLen = oldTab.length; int newLen = oldLen * 2; Entry[] newTab = new Entry[newLen]; int count = 0; for (int j = 0; j < oldLen; ++j) { Entry e = oldTab[j]; if (e ! = null) { ThreadLocal<? > k = e.get(); if (k == null) { e.value = null; // Help the GC } else { int h = k.threadLocalHashCode & (newLen - 1); while (newTab[h] ! = null) h = nextIndex(h, newLen); newTab[h] = e; count++; } } } setThreshold(newLen); size = count; table = newTab; }Copy the code

For the above source analysis content, summarized as follows:

For different ThreadLocal instances of the same thread, these ThreadLocal instances share a table array, and each ThreadLocal instance has a different subscript I in the array.

For a ThreadLocal, its subscript value I is fixed, and different threads access the same position of different table array, namely table[I], but the table between different threads is independent.

Set () source code parsing

Public void set(T value) {Thread T = thread.currentThread (); ThreadLocalMap map = getMap(t); // If map exists if (map! Map. set(this, value); Else create ThreadLocalMap and createMap(t, value); }Copy the code

Get () source code parsing

public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map ! Threadlocalmap. Entry e = map.getentry (this); if (e ! + + + + = null) {@suppressWarnings ("unchecked") // Get Entry value T result = (T)e.value; return result; } } return setInitialValue(); }Copy the code
private Entry getEntry(ThreadLocal<? Int I = key.threadLocalHashCode & (table.length-1); Entry e = table[I]; if (e ! = null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); }Copy the code

Application scenarios

ThreadLocal is very common in the framework implementation and actual development, using the characteristics of ThreadLocal can achieve thread data isolation, so as to solve the problem of multi-thread data conflict. Consider using ThreadLocal when some data is thread-scoped and different threads have different copies of the data.

Application in Spring transactions

Spring uses ThreadLocal to ensure that database operations in a single thread are using the same database connection, and this approach enables the business layer to use transactions without having to sense and manage connection objects, and manage switching, suspension, and recovery between multiple transaction configurations through propagation levels. Inside the Spring TransactionSynchronizationManager exist in a class, the class implements the decoupling of transaction management and data access service. At the same time, it also ensures the thread safety of connection in multi-threaded environment.

In Spring, the most primitive way to get dao layer beans is through getBean()

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-jdbc.xml");

UserDaoImpl userDaoImpl = (UserDaoImpl) ac.getBean("userDaoImpl");

System.out.println(userDaoImpl.insertUserInfo("zhangsan", 25));
Copy the code

For Spring’s transaction implementation, whenever there is a transaction configuration on a method, class, or interface of a class, Spring will broker instances of that class, so userDaoImpl is a reference to the proxy instance of the userDaoImpl instance, not to the target instance of userDaoImpl.

If the target method is decorated with @Transaction, then the proxy method performs enhancement (determines if the current thread has a connection, creates and binds to the current thread if it doesn’t, etc.), and then executes the target method via reflection. Finally, go back to the proxy method for enhancement (transaction rollback or transaction commit, Connection return connection pool). ThreadLocal is used here to bind connection to the current thread.

Application in business

Incorrect online date

SimpleDateFormat is often used in development for date formatting. When the SimpleDateFormat parse () method is called for date parsing, the calendar.clear () inside SimpleDateFormat is called first. Calendar.add() is then called. If one thread first calls add() and then another thread calls clear(), the parse method will parse the wrong time, resulting in incorrect dates for some users.

Solution: To solve this problem, let each thread have its own SimpleDataFormat, but the performance of the direct new method is not good, so ThreadLocal can solve this problem. Wrapping SimpleDataFormat with thread pools and ThreadLocal so that each thread has a copy of SimpleDataFormat solves thread-safety problems and improves performance.

Parameter passing across service methods

In project development, it is possible to have a thread that spans several services and several method calls, often passing some state information, such as user authentication information. If you want to do this, one way to do it is to pass parameters through the Context object, but passing parameters through the Context might cause the parameters not to pass in, so use ThreadLocal. Once the data is set, as long as it is in the same thread, you need get elsewhere.

ThreadLocal classic problem memory leak

A memory leak

What is a Memory leak

One of the classic problems with ThreadLocal is memory leaks. A memory leak is a condition in which a program fails to free up allocated memory. A memory leak can be negligible, but the accumulation of memory leaks is very serious, no matter how much memory, will be used up sooner or later. In a nutshell: memory that is not being used by objects or variables cannot be reclaimed.

Four reference types for Java objects

To understand memory leaks, you must first understand the four types of references in JAVA objects: strong, soft, weak, and virtual.

Strong references: The most common way of referring to an object, indicating that it is in a useful and necessary state. If an object has a strong reference, GC does not reclaim it, even if the heap is out of memory.

User user = new User();

Soft reference: Indicates that an object is in a useful and non-necessary state. If an object is in a soft reference state, GC will not reclaim it if there is enough memory, but will reclaim it before OOM exception occurs if there is not enough memory. It is important to note, however, that because of the low GC thread priority, soft references are not immediately reclaimed.

User user = new User();
SoftReference softReference = new SoftReference(user);
Copy the code

Weak reference: Indicates that an object is in a potentially useful and unnecessary state. When a GC thread scans an area of memory, once it finds a weak reference, it will reclaim the object associated with the weak reference. For the collection of weak references, it does not matter whether the memory area is sufficient or not, if found, it will be reclaimed. Also, because the GC thread priority is low, all weak references will not be collected immediately.

User user = new User();
WeakReference weakReference = new WeakReference(user);
Copy the code

Virtual reference: Indicates that an object is in a useless state. It can be garbage collected at any time and the use of virtual references must be used in conjunction with the Reference Queue

User user = new User();
ReferenceQueue referenceQueue = new ReferenceQueue();
PhantomReference phantomReference = new PhantomReference(user,queue);
Copy the code

Cause analysis of memory leakage

According to the previous source code analysis of ThreadLocal, each Thread maintains a ThreadLocalMap, and the Entry object in ThreadLocalMap inherits WeakReference. Where key is a ThreadLocal instance using a weak reference and value is a copy of the thread variable.

static class Entry extends WeakReference<ThreadLocal<? >> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<? > k, Object v) { super(k); value = v; }}Copy the code

So why define a key as a ThreadLocal with weak references? If the key is defined as a strong reference, when a ThreadLocal is reclaimed, ThreadLocalMap also holds a strong reference to ThreadLocal. If it is not manually deleted, the ThreadLocal will not be reclaimed, resulting in an Entry memory leak.

To avoid this problem, the key is defined as a weak reference, but when GC occurs, the key will be reclaimed because it is a weak reference, but the value will still exist because it is a strong reference, resulting in a memory leak of the value.

It is also very simple to avoid the occurrence of ThreadLocal memory leaks. For ThreadLocal use, be sure to perform remove in the last step.