Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to close Resource Resolver and Session both?

Tags:

aem

aem-6

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

like image 911
Oliver Avatar asked Jan 20 '26 18:01

Oliver


1 Answers

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.

like image 147
Jens Avatar answered Jan 22 '26 14:01

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!