This article is the first complementary module to the previous article on Java’s Most Common 200+ Interview Questions.

Let us have progress every day, Lao Wang take you to create the most complete Java interview list, seriously do one thing to the extreme.

1. What is ThreadLocal?

ThreadLocal is a local thread copy variable utility class. It is mainly used to make a mapping between the private thread and the copy object stored by the thread. The variables between each thread do not interfere with each other. In high concurrency scenarios, stateless calls can be realized, and it is suitable for the operation that each thread does not share variable values.

2. How does ThreadLocal work?

ThreadLocal principle: Each thread maintains a ThreadLocalMap, which is a Map (key,value) data format. The key is a weak reference, which is the ThreadLocal itself, and the value stores the value of the thread variable.

That is, ThreadLocal itself does not store the values of variables in a thread; it is a tool that maintains a Map within the thread to help store and fetch variables.

Data structure, as shown below:

(Photo from Internet)

3. How does ThreadLocal resolve Hash conflicts?

Unlike HashMap, the ThreadLocalMap structure is very simple and has no next reference, which means that the resolution of Hash conflicts in ThreadLocalMap is not a list but a linear probe. The so-called linear detection is to determine the position of the element in the table array according to the hashcode value of the initial key. If it is found that this position has been occupied by other key values, the fixed algorithm is used to find the next position of a certain step length and judge successively until the position that can be stored is found.

The source code implementation is as follows:

/
 * Increment i modulo len.
 */
private static int nextIndex(int i, int len) {
    return ((i + 1 < len) ? i + 1 : 0);
}

/
 * Decrement i modulo len.
 */
private static int prevIndex(int i, int len) {
    return ((i - 1> =0)? i -1 : len - 1);
}
Copy the code

4. What about memory leaks in ThreadLocal?

ThreadLocal is referred to as a weak reference by the Key in the Entry in the ThreadLocalMap, so if a ThreadLocal has no external strong reference to reference it, then the ThreadLocal will be collected in the next JVM garbage collection. In this case, the key in the Entry is already collected, but the value is a strong reference that is not collected by the garbage collector. Thus, if the ThreadLocal thread keeps running, the value will never be collected, and a memory leak will occur.

5. Why is ThreadLocalMap’s key a weak reference?

In ThreadLocalMap, the key is a weak reference, and the value is a strong reference.

  • Key uses strong references: This leads to a problem where the object referenced by ThreadLocal is reclaimed, but ThreadLocalMap also holds a strong reference to ThreadLocal, which will not be reclaimed if it is not manually removed, resulting in a memory leak.
  • Key uses weak references: In this case, the referenced ThreadLocal object is reclaimed, and since ThreadLocalMap holds a weak reference to ThreadLocal, the ThreadLocal is reclaimed even without manual deletion. The value is cleared the next time ThreadLocalMap calls set, get, and remove.

Comparing the above two cases, we can find that: The lifetime of a ThreadLocalMap is the same as that of a Thread, so if you do not manually delete the corresponding key, you will cause a memory leak. The optimal solution is that the corresponding value is cleared the next time ThreadLocalMap calls set, GET, and remove.

6. What are the application scenarios of ThreadLocal?

ThreadLocal is suitable for independent variable copies, such as Hibernate’s session fetch scenario.

Sample code:

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

public static Session getCurrentSession(a){
    Session session =  threadLocal.get();
    try {
        if(session ==null&&! session.isOpen()){/ /...
        }
        threadLocal.set(session);
    } catch (Exception e) {
        // TODO: handle exception
    }
    return session;
}
Copy the code

Check out all the interview questions: Java’s most Common 200+ Interview Questions

The resources

www.jianshu.com/p/a1cd61fa2…

www.jianshu.com/p/98b68c97d…

Scan the QR code below for more updates:

Related articles recommended:

Java most common 200+ interview questions