Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

AEM Tip: Creating a Helper to Close Sling Resource Resolver Instances | AEM Community Blog Seeding

Community Manager
Community Manager


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


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.)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResourceResolverDecorator implements AutoCloseable {

private static final Logger LOG = LoggerFactory.getLogger(ResourceResolverDecorator.class);

public ResourceResolver resolver;
boolean saveOnClose;

public ResourceResolverDecorator(ResourceResolverFactory factory) throws LoginException {
this(factory, true);

public ResourceResolverDecorator(ResourceResolverFactory factory, boolean saveOnClose) throws LoginException {
resolver = factory.getServiceResourceResolver(...);
this.saveOnClose = saveOnClose;

public ResourceResolver getResolver() {
return resolver;

public void close() throws Exception {
if (resolver != null && resolver.isLive()) {
if (saveOnClose) {

public void saveChanges() {
if (resolver.hasChanges()) {
try {
} catch (PersistenceException e) {
LOG.error(e.getMessage(), e);

Read Full Blog

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


Please use this thread to ask the related questions.


Topics help categorize Community content and increase your ability to discover relevant content.

0 Replies