public static <T> T doLookup(String name) throws NamingException { return (T) (new InitialContext()).lookup(name); }
Doesn't InitialContext.doLookup() bring resource leak?
TweetPosted on Thursday Feb 12, 2015 at 12:00PM in Technology
There’s a convenient static method called InitialContext.doLookup() which introduced at Java6. it uses Generics so we don’t need to cast returned object by hand. implementation is very simple as follows:
I think it’s bad because there’s no way to invoke InitialContext#close() because doLookup()
doesn’t save the reference to InitialContext
instance anywhere. if it acquired some resource such as TCP socket it may brings resource leak.
Personally I will avoid use of doLookup()
because of this reason while there are many opinion that it doesn’t need to close explicitly at most of environments. I guess I’m too sensitive about it but I have a history of strugging with leak of JDBC resources (Connection
, Statement
and ResultSet
) so I’m very curious about this kind of problem.
Sometimes handling of InitialContext
is annoying because it should be keep opened during use of returned instance on some environments or implementations. also I wonder why InitialContext
doesn’t implemented AutoCloseable
while it’s a perfect candidate for it.
For Servlets you could write as follows:
public class TestServlet extends HttpServlet { private Context context; private DataSource dataSource; @Override public void init() throws ServletException { try { context = new InitialContext(); dataSource = (DataSource) context.lookup("java:comp/env/jdbc/derby"); } catch (NamingException e) { throw new ServletException(e); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try (Connection cn = dataSource.getConnection()) { // database operations } catch (SQLException e) { throw new ServletException(e); } } @Override public void destroy() { if (context != null) { try { context.close(); } catch (NamingException e) { // no-op } } } }
In jberetweb, I wrote an interface named JobOperatorWork and a method intended to use with it called doWorkWithJobOperator() for ease of handling of InitialContext
closing.
In Java EE environment, you could simply use @Resource
or @EJB
for avoiding annoying procedure of closing.
Tags: javaee