Context and InitialContext - should I call the close () method for these objects?

If I used to look at Java SE6 documentation on Context and InitialContext, I would see that there is a close() method for everyone.

So now I wonder, do I need to call the close() method on Context / InitialContext objects?

Here is a snippet of my typical servlet code and how the Context / InitialContext object is used.

 public class MyTypicalServlet extends HttpServlet { //thread safe DataSource ds; String FilePath; public void init(ServletConfig config) throws ServletException { super.init(config); try { final Context ctx = new InitialContext(); ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myDB"); FilePath = getServletContext().getInitParameter("FilePath"); } catch (NamingException e) { throw new ServletException("Unable to find datasource: " + e.getMessage(), e); } } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //...a bunch of code } }//class 
+7
source share
2 answers

Good habit. For example, I should always close my InputStream classes, even if I use ByteArrayInputStream, where the close () method is non-op. Thus, if I change it to some other implementation later, that is not all that needs to be changed.

In the same case - if you call close (), you will be more compatible with any JNDI implementation.

+6
source

The close method allows you to free resources used by the context, instead of waiting for the GC to free them. Perhaps this would be useful for a context that needs an open connection, for example, with a database or with an external system. But I'm sure this is not useful for the java: comp / env context. Anyway, I never saw any code covering them.

+7
source

All Articles