首页 > 解决方案 > 覆盖“线程释放时”行为的方法名称或机制是什么

问题描述

我想覆盖行为,以便ExecutorService调用自定义方法。当一个线程被释放时,我想清除所有ThreadLocal变量。对 api 不是很熟悉,或者可能已经存在一些东西。

不确定线程​​池在完成工作时如何管理线程,但我认为它不会破坏它们,因为如果它不破坏它们,那么根据 ThreadLocal 描述,这将是昂贵的:

Each thread holds an implicit reference to its copy of a thread-local
 * variable as long as the thread is alive and the {@code 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

标签: javamultithreading

解决方案


对于一个ExecutorService你可以做一个自我清洁的任务。

public CleanerTask implements Runnable {
    private Disposable realRunnable;

    public CleanerTask(Disposable d) {
        realRunnable = d;
    }

    public void run() {
        realRunnable.run();
        realRunnable.dispose();
    }
}

在这个例子Disposable中是一个接口扩展Runnable并提供了一个dispose()清理ThreadLocal变量的方法。该实现保证run()dispose()在同一个线程中运行,因此可以安全地清除变量。

然后,您只需要确保在将任务CleanerTask提交给执行者之前将它们包装在 a 中。


但是,如果你不依赖于ExecutorService你可以扩展ThreadPoolExecutor它提供了一个afterExecute方法。然后你就打电话给dispose()那里(在检查Runnable了正确的类型之后)。

(我一开始以为afterExecute没有在运行任务的线程中运行,但幸运的是我想错了。)


推荐阅读