持有对 Thread 对象的引用会导致内存泄漏吗?
Would holding a reference to a Thread object cause memory leak?
我想写一个代理来确保一个特定的对象只在一个特定的线程上使用,所以我需要持有一个对 Thread
对象的引用(正如 JavaDoc 所说的 id 可以重用).此引用是否会导致线程(而不是 Thread 对象)在终止时未被完全垃圾回收?
I want to write a proxy to ensure a particular object is only ever used on a particular thread, so I need to hold a reference to the Thread object
你不知道。您可以使用仅在特定线程中设置的 ThreadLocal<Boolean>
。
Would this reference cause the thread (not the Thread object) to not be fully garbage collected when it terminates?
您的引用会导致 Thread
泄漏,但正如@superbob 所写,未指定 OS 线程会发生什么。我不在乎,只要你知道它真的只是一个线程。
虽然 ThreadLocal
也可能 leak,但没有子类化的简单 ThreadLocal<Boolean>
(尤其是不使用 initialValue()
)不会泄漏任何内容。
The external library I use has an object pool, but somewhere in the code base objects are being returned to the pool prematurely resulting in a non-thread-safe object being used on multiple threads. I want to write a proxy to detect such case. The proxy should store a reference to the currentThread when the object was taken out of the pool and throw if the calling thread is different from the stored Thread.
这听起来与您的问题大相径庭,似乎使我的上述回答无效。很久以前写过这样的东西:
import com.google.common.collect.MapMaker;
public static synchronized boolean singleThreaded(Object o) {
final Thread neu = Thread.currentThread();
final Thread old = threadMap.put(o, neu);
return old==null || old==neu;
}
private final static Map<Object, Thread> threadMap =
new MapMaker().weakKeys().weakValues().makeMap();
并在调试时使用它以确保 someObject
通过
在单个线程中使用
assert singleThreaded(someObject)
由于所有参考文献都很弱,我希望没有泄漏
我想写一个代理来确保一个特定的对象只在一个特定的线程上使用,所以我需要持有一个对 Thread
对象的引用(正如 JavaDoc 所说的 id 可以重用).此引用是否会导致线程(而不是 Thread 对象)在终止时未被完全垃圾回收?
I want to write a proxy to ensure a particular object is only ever used on a particular thread, so I need to hold a reference to the Thread object
你不知道。您可以使用仅在特定线程中设置的 ThreadLocal<Boolean>
。
Would this reference cause the thread (not the Thread object) to not be fully garbage collected when it terminates?
您的引用会导致 Thread
泄漏,但正如@superbob 所写,未指定 OS 线程会发生什么。我不在乎,只要你知道它真的只是一个线程。
虽然 ThreadLocal
也可能 leak,但没有子类化的简单 ThreadLocal<Boolean>
(尤其是不使用 initialValue()
)不会泄漏任何内容。
The external library I use has an object pool, but somewhere in the code base objects are being returned to the pool prematurely resulting in a non-thread-safe object being used on multiple threads. I want to write a proxy to detect such case. The proxy should store a reference to the currentThread when the object was taken out of the pool and throw if the calling thread is different from the stored Thread.
这听起来与您的问题大相径庭,似乎使我的上述回答无效。很久以前写过这样的东西:
import com.google.common.collect.MapMaker;
public static synchronized boolean singleThreaded(Object o) {
final Thread neu = Thread.currentThread();
final Thread old = threadMap.put(o, neu);
return old==null || old==neu;
}
private final static Map<Object, Thread> threadMap =
new MapMaker().weakKeys().weakValues().makeMap();
并在调试时使用它以确保 someObject
通过
assert singleThreaded(someObject)
由于所有参考文献都很弱,我希望没有泄漏