Home >Java >javaTutorial >How to solve java ThreadLocal memory leak

How to solve java ThreadLocal memory leak

王林
王林forward
2023-05-18 10:25:051395browse

1. Leak instance

ThreadLocalMap’s static inner class Entry:

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

ThreadLocalMap uses the static inner class Entry to implement storage, and Entry Inherits the WeakReference class, so the key in ThreadLocalMap is actually a weak reference to ThreadLocal.

Because ThreadLocalMap uses the weak reference of ThreadLocal as the key, when this ThreadLocal has no external strong reference, it will be GC. At this time, an Entry with a null key will appear in ThreadLocalMap. Of course, the value of this Entry will never be accessed.

In this case, if the current working thread has not ended, then the value with a null key is strongly referenced by Entry, and Entry is strongly referenced by the ThreadLocalMap of the current thread, causing this value to never be GC , causing a memory leak.

2. Solution

ThreadLocalMap’s cleanSomeSlots() and expungeStaleEntry() methods can clear values ​​with null keys. In the set(), get(), and remove() methods of ThreadLocal, cleanSomeSlots() or expungeStaleEntry() will be called to clear all values ​​with null keys in the ThreadLocalMap.

The above is the detailed content of How to solve java ThreadLocal memory leak. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete