2

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

Oliver
  • 6,152
  • 2
  • 42
  • 75
  • 2
    Ownership rule applies. you open it --> you close it! Go through the [rules](https://cqdump.wordpress.com/2013/07/23/cq-development-patterns-sling-resourceresolver-and-jcr-sessions/) for clarification – Ulug Toprak Aug 16 '17 at 14:38
  • Possible duplicate of [Should I close the session before closing the resource resolver](https://stackoverflow.com/questions/37880336/should-i-close-the-session-before-closing-the-resource-resolver) – dzenisiy Aug 17 '17 at 09:14

2 Answers2

9

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.

Jens
  • 20,533
  • 11
  • 60
  • 86
2

Closing one will close them both. If you log a message or debug, you will see you don't enter that second if statement.

bfitzpatrick
  • 1,513
  • 11
  • 13
  • 1
    Closing resourceResolver close also the session, but it does not work in the same way if you close session only, resourceResolver will still be available and exception "Session is closed" will be thrown whenever the same resourceResolver will be invoked (AEM caches opened resourceResolver in some pool, so it is possible to get the same resourceResolver when requesting for the resourceResolver) – rzasap Aug 17 '17 at 12:40