Hi, everyone.
I think I have part of the answer, maybe the whole answer. A google search on "static inner class ThreadLocal" returns a blog thread by Crazy Bob (who ain't so crazy sometimes
), that kind of explains why the inner class needs to be static for ThreadLocal use:
http://crazybob.org/2006/02/threadlocal-memory-leak.html ...basically it's "insurance" against memory leaks caused by strong references to the outer class, if I'm understanding this correctly.
That would mean that Mr. Goetz's code needs to be changed to this, in order to compile correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class
Test {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
Connection initConn = null;
try {
initConn = DriverManager.getConnection("someURL");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return initConn;
}
}
private static ThreadLocalConnection conn = new ThreadLocalConnection();
public static Connection getConnection() {
return (Connection) conn.get();
}
}
Using the above as a pattern, I created other such "Dispensers" for Spring objects (but not Connections), and they appear to run correctly. I say "appear", because I would still like some confirmation that I'm understanding this correctly from a second source (other that Crazy Bob). I would sure be nice if Sun or someone in authority would state why these need to be static, as I'm still having a bit of trouble visualizing it in relation to ThreadLocal.
In any case, as a side-benefit, using the above, I can do all my Spring stuff programattically, i.e. I'm not having to do anything in the Spring bean xml config files, but am still getting most of the benefit of the Spring classes.
Ben