Search code examples
aemaem-6

Do we need to close Resource Resolver and Session both?


I am getting a ResourceResolver Object from ResourceResolverFactory i.e. I am creating this resourceResolver and I am adapting to Session.

Session session = resourceResolver.adaptTo(Session.class);

Do I need to close both, the resolver and the session or closing one would be suffice?

finally {
    if (session != null && session.isLive()) {
        session.logout();
    }

    if (resourceResolver != null && resourceResolver.isLive()) {
        resourceResolver.close();
    }
}

This question is about "should we be closing both" and not which to close first


Solution

  • The ResourceResolver will close the underlying Session when you call the ResourceResolver.close() method.

    If you use newer versions of Sling I would advise you to use the try-with-resource construct when you use ResourceResolver:

    try (final ResourceResolver resolver = this.getResourceResolver()) {
        [... use resolver here ...]
    }
    

    Since ResourceResolver implements the AutoClosable interface it can be used with try-with-resource. This will always close the ResourceResolver and you will not have to deal with exceptions etc.

    Beware that you can only do this with ResourceResolvers that you created. If you use the ResourceResolver that you get from a Resource for example you should not close it. It is considered best practice that only the one who created the ResourceResolver should close it.