mardi 19 mai 2015

When to close the JNDI Context

When we do a lookup of an object via JNDI, we do something like this:

public SomeResult doSomething() {
  Context ctx;
  try {
    ctx = new InitialContext(properties);
    SomeClass someObject = (SomeClass) ctx.lookup("jndiName");
    SomeResult someResult = someObject.getResult();
    return someResult
  } finally {
      ctx.close();
  }
}

A colleague did it somewhat differently like this:

public SomeClass getSomeClass() {
  Context ctx;
  SomeClass someObject = null;
  try {
    ctx = new InitialContext(properties);
    SomeClass someObject = (SomeClass) ctx.lookup("jndiName");
    return someObject
  } finally {
    ctx.close();
  }
}

That got me wondering, which one to use? Is the returned object even valid after closing the Context? Does this work via sheer coincident or is the context just for looking up and the object (as a proxy to the ejb) is self-sustained?

I tried to find something in the JNDI-Spec... but got nothing... but I may be just blind ;-)

What are the best practices to lookup a EJB via JNDI and using it, and for what reasons.

Aucun commentaire:

Enregistrer un commentaire