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

kautuk_sahni
Community Manager
Community Manager

BlogImage.jpg

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

Abstract

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 org.apache.sling.api.resource.ResourceResolver class used in AEM versions before 6.2 don’t implement either java.io.Closeable or the java.lang.AutoCloseable interfaces. (Check uber-jar for 6.0.1 to see for yourself.)

import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.ResourceResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.sling.api.resource.ResourceResolverFactory;

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;
}

@Override
public void close() throws Exception {
if (resolver != null && resolver.isLive()) {
if (saveOnClose) {
saveChanges();
}
resolver.close();
}
}

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

Read Full Blog

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

Q&A

Please use this thread to ask the related questions.

Topics

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

0 Replies