Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context and InitialContext - should I be calling the close() method on these objects?

Tags:

java

servlets

Had I looked into the Java SE6 documentation sooner on Context and InitialContext, I would've seen that there is a close() method for each.

So now I wonder, do I need to call the close() method on the 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        
like image 241
katura Avatar asked Feb 25 '11 18:02

katura


2 Answers

It's a good habit to get into. For example, I always make sure to close my InputStream classes, even if I'm using a ByteArrayInputStream, where the close() method is a no-op. That way, if I change it to some other implementation later, it's one less thing to have to change as well.

Same case here - if you call close(), you'll be more compatible with any JNDI implementation.

like image 81
Jesse Barnum Avatar answered Nov 09 '22 10:11

Jesse Barnum


The close method allows releasing resources used by the context instead of waiting for the GC to release them. It would perhaps be useful for a context needing an open connection to, for example, a database or an external system. But I'm pretty sure it isn't useful for the java:comp/env context. Anyway, I've never seen any code closing them.

like image 43
JB Nizet Avatar answered Nov 09 '22 12:11

JB Nizet