ThreadLocal Resource
When I strongly reference ThreadLocal
holding a resource as shown in below example;
private final static ThreadLocal<InputStream> resource =开发者_Python百科 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?
The inputstream in the threadlocal is not stored via weakreference(its stored by a normal strong reference), hence as long as the threadlocal object itself is available, your inputstream in it will be available too, until you call remove().
But the threadlocal itself is stored as a weak-reference in the ThreadLocalMap for each thread. The idea is each Thread has a field for ThreadLocalMap where all the threadlocals are keyed with weak-references with corresponding values.
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.
精彩评论