简体   繁体   English

Context和InitialContext - 我应该在这些对象上调用close()方法吗?

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

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. 如果我在Context和InitialContext上更早地查看Java SE6文档,我会看到每个文件都有一个close()方法。

So now I wonder, do I need to call the close() method on the Context/InitialContext objects? 所以现在我想知道,我是否需要在Context / InitialContext对象上调用close()方法?

Here is a snippet of my typical servlet code and how the Context/InitialContext object is used. 这是我的典型servlet代码片段以及C​​ontext / InitialContext对象的使用方式。

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        

The close method allows releasing resources used by the context instead of waiting for the GC to release them. close方法允许释放上下文使用的资源,而不是等待GC释放它们。 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. 但我很确定它对java:comp / env上下文没用。 Anyway, I've never seen any code closing them. 无论如何,我从未见过关闭它们的任何代码。

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. 例如,我总是确保关闭我的InputStream类,即使我使用的是ByteArrayInputStream,其中close()方法是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. 同样的情况 - 如果你调用close(),你将与任何JNDI实现更兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM