gpt4 book ai didi

java - 线程本地资源

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:56:14 27 4
gpt4 key购买 nike

当我强烈引用 ThreadLocal 持有资源时,如下例所示;

private final static ThreadLocal<InputStream> resource = new ThreadLocal<InputStream>()
{
@Override
protected InputStream initialValue()
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream input = loader.getResourceAsStream("doc/doc.xml");
if (input == null) throw new RuntimeException("Could not locate doc.xml");
return input;
}
};

ThreadLocal 中的 InputStream 在什么时间/范围内不可用。我想知道是否在某个时候未使用 ThreadLocal 对象时,JVM 将垃圾收集其引用,因此无法访问嵌套的 InputStream

javadoc 表明;

All of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

如果是这种情况,那么如何确保副本始终可用?

最佳答案

threadlocal 中的输入流不是通过弱引用存储的(它由普通的强引用存储),因此只要 threadlocal 对象本身可用,您在其中的输入流也将可用,直到您调用 remove() .

但 threadlocal 本身作为弱引用存储在 ThreadLocalMap 中对于每个线程。这个想法是每个 Thread 都有一个 ThreadLocalMap 字段,其中所有 threadlocals 都使用具有相应值的弱引用键控。

关于java - 线程本地资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6466283/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com