ThreadLocal资源(ThreadLocal Resource)

编程入门 行业动态 更新时间:2024-10-26 13:22:50
ThreadLocal资源(ThreadLocal Resource)

当我强烈引用持有资源的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表明;

它的所有线程局部实例副本都要进行垃圾回收(除非存在对这些副本的其他引用)。

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

When I strongly reference ThreadLocal holding a resource as shown in below example;

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; } };

At what point in time/scope will the InputStream held in the ThreadLocal not be avaliable. I want to know if at some point when the ThreadLocal object is not used, the JVM will garbage collect its reference and hence access to nested InputStream will not be available for usage.

The javadoc indicate that;

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

If this is the case, then how do one make sure a copy is constantly available?

最满意答案

您的代码的问题是您将保持文件指针打开。 您可以将对象存储在ThreadLocal中,但不存储诸如文件句柄,数据库连接或其他需要关闭的资源等资源。 ThreadLocal将超出范围,因此一旦Thread完成就会被垃圾收集。 在您的情况下,我将存储您从ThreadLocal中的InputStream获取的内容,但不存储流本身。 如果您想确保某些内容始终可用,请使用Singleton模式。 请注意Java EE环境中模式的局限性。

The problem with your code is that you will keep a file pointer open. You can store Objects in a ThreadLocal, but do not store resources such as file handles, db connections or other resources that need to be closed. The ThreadLocal will go out of scope and therefore be garbage collected once the Thread has completed. In your case I would store the contents of what you are getting from the InputStream in the ThreadLocal but not the stream itself. If you want to make sure something is always available use the Singleton pattern. Be aware of the limitations of the pattern in the Java EE environment.

更多推荐

本文发布于:2023-08-04 15:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417830.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资源   ThreadLocal   Resource

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!