我们是否应该始终在 JBoss 应用程序的客户端关闭 javax.naming.InitialContext?

Should we always close javax.naming.InitialContext at client side of JBoss app?

当我们创建一个新的 InitialContext 用于远程访问 Enterprise Java Beans 时,工作完成后,我们是否应该始终通过 context.close() 关闭 context

这是一个代码示例:

// 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();
            }
        }
    }

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

尽管垃圾收集器会收集它们,但您不必等待 gc,您应该 close 通过提供的函数收集它们。所以,我的回答是,是的,你应该关闭这个以及任何其他应该关闭的资源。