When we create a new InitialContext
for remote access to Enterprise Java Beans, after work is done, should we always close the context
via context.close()
?
Here is a code sample:
// Client side method
private void doSomeActionMethod() {
RouteTransactionFacadeBeanRemote remote = null;
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = null;
try {
context = new InitialContext(jndiProperties);
remote = (RouteTransactionFacadeBeanRemote) context
.lookup("ejb:EJBEAR/EJBServer//RouteTransactionFacadeBean!facade.RouteTransactionFacadeBeanRemote");
//DO SOMETHING WITH REMOTE EJB
} catch (NamingException e) {
e.printStackTrace();
} finally {
try {
// Should we always do this?
if (context != null) context.close();
} catch (NamingException ex) {
ex.printStackTrace();
}
}
}
From javadocs:
Closes this context. This method releases this context's resources immediately, instead of waiting for them to be released automatically by the garbage collector. This method is idempotent: invoking it on a context that has already been closed has no effect. Invoking any other method on a closed context is not allowed, and results in undefined behaviour.
Although, garbage collector will collect them but instead of waiting for gc
, you should close
it by the provided function. So, my answer is, yes you should close this as well as any other resource that should be closed.