1. Introduction

I’ve been hearing about memory leaks in ThreadLocal for a long time, and I’ve read about them. I’ve probably figured out why they happen, but after a while I’ve forgotten the root cause. To get to the bottom of this question, this article was created.

2. Thread the Thread

To understand ThreadLocal, we have to mention threads. The Thread contains a reference to ThreadLocalMap. The key of ThreadLocalMap refers to ThreadLocal, and the value is the value set by the user.

3.ThreadLocal

3.1 Sample code for using ThreadLocal

public class ThreadLocalUtils { private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void set(Integer value) { threadLocal.set(value); } public static Integer get() { return Objects.nonNull(threadLocal.get()) ? threadLocal.get() : null; } public static void remove() { threadLocal.remove(); }}Copy the code

Figure 3.2 memory

Given the sample code and the memory map, let’s look at why ThreadLocal is leaking memory

3.3 Memory Leak Scenario

Currentthreads are not recycled when used by threads (thread pools), and memory leaks can occur if the value in an Entry occupies too much memory

3.4 Security Scenario

  • When the method completes, the thread is released,Thread threadtoCurrentThreadThe reference will break,GCafterCurrentThreadIt will be reclaimed, in which case there will be no memory leak
  • When using theThreadLocalAfter the callremove()Methods also do not leak memory

4. To summarize

To avoid memory leaks with ThreadLocal, either ensure that the thread is not recycled or display its remove() method. It is recommended to display the remove() method after using it.