如何在没有实际执行的情况下测试ThreadLocal是否已初始化? [英] How to test if a ThreadLocal has been initialized without actually doing that?
问题描述
我想测试是否已初始化 ThreadLocal
而未实际初始化它。当然,代码需要是线程安全的。理想情况下我想要这样的东西:
I want to test if a ThreadLocal
has been initialized without actually initializing it. Of course, the code needs to be thread-safe. Ideally I want something like this:
class TestableThreadLocal<T> extends ThreadLocal<T> {
public boolean isInitialized() {
...
}
}
但是我如何实现这个方法呢?
But how would I implement this method?
编辑:动机:我已经子类化了 ThreadLocal
覆盖 initialValue()
。但是,我并不总是需要初始化,特别是因为它可能会导致多类加载器环境中的内存泄漏。一个简单的测试可以帮助我编写代码以避免意外初始化。
Motivation: I have subclassed a ThreadLocal
to override initialValue()
. However, I do not always need the initialization, in particular because it could cause a memory leak in multi-classloader environments. A simple test would help me write code to avoid the accidental initialization.
推荐答案
我倾向于使用简单的规则来避免类加载器泄漏,诚然,它们很麻烦,但有一些包装并没有那么糟糕。是的,泄密是邪恶的。
I tend to use simple rules to avoid classloader leaks, admittedly they are cumbersome but with some wrapping it's not that bad. Yes, leaks are evil.
- 不覆盖
initialValue
,永远 - 你是只是要求麻烦,只是忘记它存在。 - 除非你做
threadLocal.set(xxx),否则不要在ThreadLocal中存储非系统/非bootstap类; try {... process ...} finally {threadLocal.set(null);}
- 如果仍然覆盖initialValue,请使用
threadLocal.remove()
不是threadLocal.set(null)
- 或使用
WeakReferene
(即ThreadLocal< WeakReference< Foo>>
),用于保存硬引用的池中的值。它可能看起来很直观但是一旦清除了池,值就会消失,类可以自由地进行GC
- do no override
initialValue
, ever - you are just asking for trouble, just forget it exists. - do not store non-system/non-bootstap classes in the ThreadLocal unless you do
threadLocal.set(xxx); try{...process...}finally{threadLocal.set(null);}
- if you still override initialValue, use
threadLocal.remove()
notthreadLocal.set(null)
- or use
WeakReferene
(i.e. ThreadLocal<WeakReference<Foo>>
) for the value from a pool that keeps the hard references. It might look counter intuitive but once the pool is cleared the values disappear and the classes are free to be GC'd
我意识到帖子不是对你的问题的直接回复,但是没有简单的方法来达到你想要的目的并防止泄密。
I realize the post is not a direct reply to your question, however there is no simple way to achieve what you wish and keep the leaks at bay.
这篇关于如何在没有实际执行的情况下测试ThreadLocal是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!