Search code examples
sling

When to explicitly close ResourceResolver in Sling


I've read on this blog about how to use resourceResolver properly. The author quotes

If you open a JCR session of a Sling ResourceResolver, you are also responsible for closing it. On the other hand: If you get passed a ResourceResolver or a Session object, do not call logout() or close() on it.

I'm not able to grasp this concept, may be because of no code example in this case.

From what i know, i can get a ResourceResolver object via either request.getResourceResolver() in servlets, using @Reference SCR annotation in OSGi components, jsp's implicit resourceResolver object, using sling.getService() in jsp, and also via adapting to ResourceResolver object.

In all the ways of getting resourceResolver object, which ones should i close myself and what is the session associated with each of these objects ?


Solution

  • Think of it like a File resource.

    • if you open it, you are responsible for closing it
    • if you use a reference to the File, then it is not your responsibility to close it

    Therefore, your code should open & close in the same scope.

    If you obtain a resourceResolver FROM a resource, you did not open the resolver and you do not need to close it.

    In the example from the blog, they generate a session from session = repo.loginAdministrative() (Repository no longer has this method); thus is responsible for calling session.logout() in the same scope (using the finally {...} block).