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?
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.