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
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.