Proper handling of javax.naming.InitialContext

Discussions

General J2EE: Proper handling of javax.naming.InitialContext

  1. Proper handling of javax.naming.InitialContext (2 messages)

    I've seen conflicting advice on the proper lifetime of a javax.naming.InitialContext object. On on hand, some people advise that an InitialContext is a limited resource, to be created when needed, and released shortly thereafter, like a database connection. Others have advised that intantiation is the only resource-intensive aspect of InitialContext, and they should be "kept around" by an object as an instance variable to avoid redundant instantiation. More simply, should InitialContexts be used like this:
    public class SimpleServlet extends HTTPServlet {
      private InitialContext myContext;

    public void init(ServletConfig _config) {
      myContext = new InitialContext();
      .....
    }

    ..some methods that use getContext()..

    private InitialContext getContext() {
      return myContext;
    }

    Or, should the context be more short lived:
    public class SimpleServlet extends HTTPServlet {

    public void init(ServletConfig _config) {
      .....
    }

    ..some methods that use getContext()..
    ..they also take care to close InitialContext objects..

    public InitialContext getContext() {
      return new InitialContext();
    }


  2. Adam,
       Yes creating an context is a little overhead .Its best to keep them around .As far as creating them in the init() is not really advisable , have a method to return the instance that u have already created .
      I have been keeping around the instance and there is no problem at all .
       why put them all in the servlet , have a class with a bunch of static methods to serve them .
      Dont do it in the init. , be aware of session beans that u might be using ( creating a session bean , means there is a time out interval associated with it), and servlets have time out interval .
     Hope this helps .
  3. I have pointed out another way (and code snippets) to keep a shared InitialContext in the thread https://www.theserverside.com/discussion/thread.jsp?thread_id=12120 .

    If you want to access the Context, just turn the getContext method public in the <X>HomeCache classes.