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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.