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
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 ResourceResolver
s 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.