Java 如何清理 ThreadLocals

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3869026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:06:44  来源:igfitidea点击:

How to clean up ThreadLocals

javatomcatthread-local

提问by Ricardo

Does any one have an example how to do this? Are they handled by the garbage collector? I'm using Tomcat 6.

有没有人有一个例子如何做到这一点?它们是否由垃圾收集器处理?我正在使用 Tomcat 6。

采纳答案by Stephen C

The javadoc says this:

javadoc 是这样说的:

"Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

“只要线程处于活动状态并且 ThreadLocal 实例可访问,每个线程都持有对其线程局部变量副本的隐式引用;在线程消失后,其线程局部实例的所有副本都受到垃圾收集(除非存在对这些副本的其他引用)。

If your application or (if you are talking about request threads) container uses a thread pool that means that threads don't die. If necessary, you would need to deal with the thread locals yourself. The only clean way to do this is to call the ThreadLocal.remove()method.

如果您的应用程序或(如果您正在谈论请求线程)容器使用线程池,则意味着线程不会死亡。如有必要,您需要自己处理线程本地人。唯一干净的方法是调用该ThreadLocal.remove()方法。

There are two reasons you might want to clean up thread locals for threads in a thread pool:

您可能希望为线程池中的线程清理线程局部变量的原因有两个:

  • to prevent memory (or hypothetically resource) leaks, or
  • to prevent accidental leakage of information from one request to another via thread locals.
  • 防止内存(或假设的资源)泄漏,或
  • 防止信息通过线程局部变量从一个请求意外泄漏到另一个请求。

Thread local memory leaks should not normally be a major issue with bounded thread pools since any thread locals are likely to get overwritten eventually; i.e. when the thread is reused. However, if you make the mistake of creating a new ThreadLocalinstances over and over again (instead of using a staticvariable to hold a singleton instance), the thread local values won't get overwritten, and will accumulate in each thread's threadlocalsmap. This could result in a serious leak.

线程本地内存泄漏通常不应该是有界线程池的主要问题,因为任何线程本地都可能最终被覆盖;即当线程被重用时。但是,如果您犯ThreadLocal了一遍又一遍地创建新实例的错误(而不是使用static变量来保存单例实例),则线程本地值不会被覆盖,并且会在每个线程的threadlocals映射中累积。这可能会导致严重泄漏。



Assuming that you are talking about thread locals that are created / used during a webapp's processing of an HTTP request, then one way to avoid the thread local leaks is to register a ServletRequestListenerwith your webapp's ServletContextand implement the listener's requestDestroyedmethod to cleanup the thread locals for the current thread.

假设您正在谈论在 webapp 处理 HTTP 请求期间创建/使用的线程本地,那么避免线程本地泄漏的一种方法是向ServletRequestListener您的 webapp注册 aServletContext并实现侦听器的requestDestroyed方法来清理线程本地当前线程。

Note that in this context you also need to consider the possibility of informationleaking from one request to another.

请注意,在这种情况下,您还需要考虑信息从一个请求泄漏到另一个请求的可能性。

回答by rustyx

There is no way to cleanup ThreadLocalvalues except from within the thread that put them in there in the first place(or when the thread is garbage collected - not the case with worker threads). This means you should take care to clean up your ThreadLocal's when a servlet request is finished (or before transferring AsyncContext to another thread in Servlet 3), because after that point you may never get a chance to enter that specific worker thread, and hence, will leak memory in situations when your web app is undeployed while the server is not restarted.

没有办法清除ThreadLocal值,除非从首先将它们放在那里的线程内部(或者当线程被垃圾收集时 - 不是工作线程的情况)。这意味着您应该在 servlet 请求完成时(或在将 AsyncContext 传输到 Servlet 3 中的另一个线程之前)小心清理 ThreadLocal,因为在那之后您可能永远没有机会进入该特定的工作线程,因此,在未重新启动服务器的情况下取消部署 Web 应用程序的情况下会泄漏内存。

A good place to do such cleanup is ServletRequestListener.requestDestroyed().

进行此类清理的好地方是ServletRequestListener.requestDestroyed()

If you use Spring, all the necessary wiring is already in place, you can simply put stuff in your request scope without worrying about cleaning them up (that happens automatically):

如果您使用 Spring,所有必要的接线已经就位,您可以简单地将内容放入请求范围内,而无需担心清理它们(自动发生):

RequestContextHolder.getRequestAttributes().setAttribute("myAttr", myAttr, RequestAttributes.SCOPE_REQUEST);
. . .
RequestContextHolder.getRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST);

回答by lyaffe

Here is some code to clean all thread local variables from the current thread when you do not have a reference to the actual thread local variable. You can also generalize it to cleanup thread local variables for other threads:

当您没有对实际线程局部变量的引用时,这里有一些代码可以清除当前线程中的所有线程局部变量。您还可以将其概括为清理其他线程的线程局部变量:

    private void cleanThreadLocals() {
        try {
            // Get a reference to the thread locals table of the current thread
            Thread thread = Thread.currentThread();
            Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            threadLocalsField.setAccessible(true);
            Object threadLocalTable = threadLocalsField.get(thread);

            // Get a reference to the array holding the thread local variables inside the
            // ThreadLocalMap of the current thread
            Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
            Field tableField = threadLocalMapClass.getDeclaredField("table");
            tableField.setAccessible(true);
            Object table = tableField.get(threadLocalTable);

            // The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
            // is a reference to the actual ThreadLocal variable
            Field referentField = Reference.class.getDeclaredField("referent");
            referentField.setAccessible(true);

            for (int i=0; i < Array.getLength(table); i++) {
                // Each entry in the table array of ThreadLocalMap is an Entry object
                // representing the thread local reference and its value
                Object entry = Array.get(table, i);
                if (entry != null) {
                    // Get a reference to the thread local object and remove it from the table
                    ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
                    threadLocal.remove();
                }
            }
        } catch(Exception e) {
            // We will tolerate an exception here and just log it
            throw new IllegalStateException(e);
        }
    }

回答by mainas

I would like to contribute my answer to this question even though it's old. I had been plagued by the same problem (gson threadlocal not getting removed from the request thread), and had even gotten comfortable restarting the server anytime it ran out of memory (which sucks big time!!).

即使它很旧,我也想为这个问题贡献我的答案。我一直被同样的问题困扰(gson threadlocal 没有从请求线程中删除),甚至在内存不足时重新启动服务器(这很糟糕!!)。

In the context of a java web app that is set to dev mode (in that the server is set to bounce every time it senses a change in the code, and possibly also running in debug mode), I quickly learned that threadlocals can be awesome and sometime be a pain. I was using a threadlocal Invocation for every request. Inside the Invocation. I'd sometimes also use gson to generate my response. I would wrap the Invocation inside a 'try' block in the filter, and destroy it inside a 'finally' block.

在设置为开发模式的 java web 应用程序的上下文中(因为服务器在每次检测到代码更改时都设置为反弹,并且可能还运行在调试模式下),我很快了解到 threadlocals 可以很棒有时会很痛苦。我对每个请求都使用了线程本地调用。在调用里面。我有时也会使用 gson 来生成我的响应。我会将 Invocation 包装在过滤器中的“try”块中,并在“finally”块中销毁它。

What I observed (I have not metrics to back this up for now) is that if I made changes to several files and the server was constantly bouncing in between my changes, I'd get impatient and restart the server (tomcat to be precise) from the IDE. Most likely than not, I'd end up with an 'Out of memory' exception.

我观察到的(我现在没有指标来支持这一点)是,如果我对几个文件进行了更改并且服务器在我的更改之间不断地跳动,我会变得不耐烦并重新启动服务器(准确地说是 tomcat)从 IDE。最有可能的是,我最终会遇到“内存不足”异常。

How I got around this was to include a ServletRequestListener implementation in my app, and my problem vanished. I think what was happening is that in the middle of a request, if the server would bounce several times, my threadlocals were not getting cleared up (gson included) so I'd get this warning about the threadlocals and two or three warning later, the server would crash. With the ServletResponseListener explicitly closing my threadlocals, the gson problem vanished.

我如何解决这个问题是在我的应用程序中包含一个 ServletRequestListener 实现,我的问题就消失了。我认为发生的事情是在请求的中间,如果服务器会反弹几次,我的 threadlocals 没有被清除(包括 gson)所以我会收到关于 threadlocals 的警告和两三个警告之后,服务器会崩溃。随着 ServletResponseListener 显式关闭我的线程局部变量,gson 问题就消失了。

I hope this makes sense and gives you an idea of how to overcome threadlocal issues. Always close them around their point of usage. In the ServletRequestListener, test each threadlocal wrapper, and if it still has a valid reference to some object, destroy it at that point.

我希望这是有道理的,并让您了解如何克服线程局部问题。始终在使用点附近关闭它们。在 ServletRequestListener 中,测试每个线程本地包装器,如果它仍然具有对某个对象的有效引用,则在此时销毁它。

I should also point out that make it a habit to wrap a threadlocal as a static variable inside a class. That way you can be guaranteed that by destroying it in the ServeltRequestListener, you won't have to worry about other instances of the same class hanging around.

我还应该指出,养成将线程局部作为静态变量包装在类中的习惯。这样您就可以保证通过在 ServeltRequestListener 中销毁它,您将不必担心同一类的其他实例闲逛。

回答by Parasu

The JVM would automatically clean-up all the reference-less objects that are within the ThreadLocal object.

JVM 会自动清理 ThreadLocal 对象中的所有无引用对象。

Another way to clean up those objects (say for example, these objects could be all the thread unsafe objects that exist around) is to put them inside some Object Holder class, which basically holds it and you can override the finalize method to clean the object that reside within it. Again it depends on the Garbage Collector and its policies, when it would invoke the finalizemethod.

清理这些对象的另一种方法(例如,这些对象可能是周围存在的所有线程不安全对象)是将它们放在某个 Object Holder 类中,该类基本上持有它,您可以覆盖 finalize 方法来清理对象驻留在其中。同样,它取决于垃圾收集器及其策略,何时调用该finalize方法。

Here is a code sample:

这是一个代码示例:

public class MyObjectHolder {

    private MyObject myObject;

    public MyObjectHolder(MyObject myObj) {
        myObject = myObj;
    }

    public MyObject getMyObject() {
        return myObject;
    }

    protected void finalize() throws Throwable {
        myObject.cleanItUp();
    }
}

public class SomeOtherClass {
    static ThreadLocal<MyObjectHolder> threadLocal = new ThreadLocal<MyObjectHolder>();
    .
    .
    .
}

回答by Philippe P.

Reading again the Javadoc documentation carefully:

再次仔细阅读 Javadoc 文档:

'Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). '

'只要线程处于活动状态并且可以访问 ThreadLocal 实例,每个线程都持有对其线程局部变量副本的隐式引用;线程消失后,它的所有线程本地实例副本都将进行垃圾回收(除非存在对这些副本的其他引用)。'

There is no need to clean anything, there is an 'AND' condition for the leak to survive. So even in a web container where thread survive to the application, as long as the webapp class is unloaded ( only beeing reference in a static class loaded in the parent class loader would prevent this and this has nothing to do with ThreadLocal but general issues with shared jars with static data ) then the second leg of the AND condition is not met anymore so the thread local copy is eligible for garbage collection.

无需清洁任何东西,泄漏存在“与”条件。因此,即使在线程存活到应用程序的 web 容器中,只要 webapp 类被卸载(只有在父类加载器中加载的静态类中的引用才会阻止这种情况发生,这与 ThreadLocal 无关,但一般问题是具有静态数据的共享 jars )然后不再满足 AND 条件的第二条腿,因此线程本地副本有资格进行垃圾收集。

Thread local can't be the cause of memory leaks, as far the implementation meets the documentation.

线程本地不能成为内存泄漏的原因,只要实现符合文档。

回答by Nathan

@lyaffe's answer is the best possible for Java 6. There are a few issues that this answer resolves using what is available in Java 8.

@lyaffe 的答案是 Java 6 的最佳答案。此答案使用 Java 8 中的可用内容解决了一些问题。

@lyaffe's answer was written for Java 6 before MethodHandlebecame available. It suffers from performance penalties due to reflection. If used as below, MethodHandleprovides zero overheadaccess to fields and methods.

@lyaffe 的答案是在MethodHandle可用之前为 Java 6 编写的。由于反射,它会遭受性能损失。如果按如下方式使用,则MethodHandle提供对字段和方法的零开销访问。

@lyaffe's answer also goes through the ThreadLocalMap.tableexplicitly and is prone to bugs. There is a method ThreadLocalMap.expungeStaleEntries()now available that does the same thing.

@lyaffe 的回答也ThreadLocalMap.table明确指出并且容易出错。ThreadLocalMap.expungeStaleEntries()现在有一种方法可以做同样的事情。

The code below has 3 initialization methods to minimize the cost of invoking expungeStaleEntries().

下面的代码有 3 种初始化方法来最小化调用成本expungeStaleEntries()

private static final MethodHandle        s_getThreadLocals     = initThreadLocals();
private static final MethodHandle        s_expungeStaleEntries = initExpungeStaleEntries();
private static final ThreadLocal<Object> s_threadLocals        = ThreadLocal.withInitial(() -> getThreadLocals());

public static void expungeThreadLocalMap()
{
   Object threadLocals;

   threadLocals = s_threadLocals.get();

   try
   {
      s_expungeStaleEntries.invoke(threadLocals);
   }
   catch (Throwable e)
   {
      throw new IllegalStateException(e);
   }
}

private static Object getThreadLocals()
{
   ThreadLocal<Object> local;
   Object result;
   Thread thread;

   local = new ThreadLocal<>();

   local.set(local);   // Force ThreadLocal to initialize Thread.threadLocals

   thread = Thread.currentThread();

   try
   {
      result = s_getThreadLocals.invoke(thread);
   }
   catch (Throwable e)
   {
      throw new IllegalStateException(e);
   }

   return(result);
}

private static MethodHandle initThreadLocals()
{
   MethodHandle result;
   Field field;

   try
   {
      field = Thread.class.getDeclaredField("threadLocals");

      field.setAccessible(true);

      result = MethodHandles.
         lookup().
         unreflectGetter(field);

      result = Preconditions.verifyNotNull(result, "result is null");
   }
   catch (NoSuchFieldException | SecurityException | IllegalAccessException e)
   {
      throw new ExceptionInInitializerError(e);
   }

   return(result);
}

private static MethodHandle initExpungeStaleEntries()
{
   MethodHandle result;
   Class<?> clazz;
   Method method;
   Object threadLocals;

   threadLocals = getThreadLocals();
   clazz        = threadLocals.getClass();

   try
   {
      method = clazz.getDeclaredMethod("expungeStaleEntries");

      method.setAccessible(true);

      result = MethodHandles.
         lookup().
         unreflect(method);
   }
   catch (NoSuchMethodException | SecurityException | IllegalAccessException e)
   {
      throw new ExceptionInInitializerError(e);
   }

   return(result);
}