AEM Tip: Creating a Helper to Close Sling Resource Resolver Instances

Share article

Tech Tips

Read our other AEM tips

Want to join our team?

Ready to start

AEM stores data in a content repository. Applications can access the repository via either Sling ResourceResolver or JCR Sessions. The former is more high-level and more convenient as an API; the latter is more low-level and less readable, but more performant. For this article, we’ll focus on Sling ResourceResolver.

Yes, we should always close ResourceResolver instances after we are done with them. (See 2nd pattern: Ownership: You open it — you close it paragraph in this blog post.) When instances are just left open, we have to deal with memory leaks.

The good news is that starting from AEM 6.2 we can leverage the try-with-resource idiom so that we never forget to close a resource resolver. Unfortunately, the class used in AEM versions before 6.2 don’t implement either or the java.lang.AutoCloseable interfaces. (Check uber-jar for 6.0.1 to see for yourself.)

However, for earlier AEM versions, we can still work around this by decorating the resource resolver to make it usable in try-with-resource constructs:

From here, we can simply create a resolver decorator within try(...), and Java will take care of calling the close() method automatically:


Author: Denis Glushkov

Here you can create the content that will be used within the module.