Home > Java > javaTutorial > body text

How to solve java ThreadLocal memory leak

王林
Release: 2023-05-18 10:25:05
forward
1363 people have browsed it

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;
        }
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template