AEM ENGINEERING / 004

Who Should Close This ResourceResolver?

A practical ownership model for request and service ResourceResolvers: scope, exception paths, borrowed sessions, async work and leak-focused tests.

SHARE
LinkedIn X Facebook Threads

Topic map

Ownership defines lifetime

ResourceResolver ownership and lifecycle

  1. 01Acquire
  2. 02Identify owner
  3. 03Use
  4. 04Copy values
  5. 05Close if owned

SYSTEM OVERVIEW

SYSTEM / FLOW

Two acquisition paths, two cleanup responsibilities.

A helper receiving a resolver does not become its owner. Returning a resource does not extend the resolver lifetime.

BORROWED REQUEST RESOLVERRequest ownsresolverHelper readsReturn valuesRequest lifecycleendsOWNED SERVICE RESOLVERApplicationacquiresBounded operationCopy resultApplicationcloses

Borrowed request resolver

  1. Request owns resolver
  2. Helper reads
  3. Return values
  4. Request lifecycle ends

Owned service resolver

  1. Application acquires
  2. Bounded operation
  3. Copy result
  4. Application closes

THIS ARTICLE EXPLORES

  1. Distinguish borrowed and owned resolvers.
  2. Keep adapted resources inside the valid lifetime.
  3. Test exceptions and asynchronous boundaries.

01 / OWNERSHIP

Start with ownership, not the variable name

Close a resolver that your code creates; do not close a resolver borrowed from the request or supplied by a caller that owns its lifecycle. A local variable named resolver does not establish ownership. Follow the acquisition path before adding close() to a finally block.

Sling documents ResourceResolver as Closeable, with a lifecycle bounded by creation and closure. Treat resources and adapted objects as scoped to that lifecycle. A helper that receives a resolver should make its borrowing contract explicit rather than unexpectedly invalidating its caller's state.

  • request.getResourceResolver(): borrowed for request processing.
  • factory.getServiceResourceResolver(...): owned by the code that acquired it.
  • resolver.clone(...): a separately acquired resolver; give the clone its own owner.
  • A resolver passed as a method parameter: ask who acquired it and who completes the operation.
Who closes it?
AcquisitionOwnerCaller action
Request resolverRequest lifecycleBorrow; do not close in the helper.
Caller parameterCalling contractDo not infer ownership from a local variable.
New service resolverAcquiring codeClose on success and exception paths.

02 / BOUNDED SCOPE

Make the service resolver scope visible

This method fragment assumes an injected ResourceResolverFactory and a configured content-reader subservice. The service mapping and repository permissions must be provisioned separately. Use a path fixed by the application; if input selects content, validate that input before repository access.

Return an immutable value from the bounded scope. Returning Resource, ValueMap or Session to code that runs after close() makes the ownership boundary ambiguous. Let LoginException remain distinct from content absence; a failed service login is not an empty search result.

02 — Make the service resolver scope visible

java
public String readTitle() throws LoginException {
    Map<String, Object> auth = Collections.singletonMap(
        ResourceResolverFactory.SUBSERVICE, "content-reader");
    try (ResourceResolver owned = factory.getServiceResourceResolver(auth)) {
        Resource page = owned.getResource("/content/example/en/jcr:content");
        return page == null ? "" : page.getValueMap().get("jcr:title", "");
    }
}

03 / SESSIONS

Do not give two layers the same cleanup job

When a Session is adapted from a resolver, avoid treating it as a separately logged-in session. Close the resolver you own rather than independently logging out its borrowed session. Conversely, a session acquired through a repository login has a different ownership contract. Check the actual acquisition API, not just the returned type.

Closing a resolver is also not a substitute for an explicit persistence decision. If the operation writes content, make its commit and failure handling visible. Avoid a generic cleanup helper that commits whatever changes happen to be pending: it can persist work the caller did not intend to save.

04 / ASYNC

Transfer a work description, not a live resolver

Sling's resolver API is generally not thread safe. A background task should acquire a resolver within its own execution scope rather than retain one from an HTTP request. Pass bounded identifiers and immutable data to a job; do not pass a request, Resource or adapted session across the boundary.

Define what happens if the target content changes before execution. For an indexing job, a missing path may mean remove the stale search document. For a publishing workflow, it may require a recorded failure. This is an application decision, not something a longer-lived resolver solves.

Cross the async boundary with values

Do not hand a request-scoped resolver to work that outlives the request.

  1. 01Read within scope
  2. 02Extract immutable values
  3. 03Queue identifiers / values
  4. 04Acquire worker-owned resolver
  5. 05Close worker scope

05 / VALIDATION

Test the ownership contract on failure paths

A successful read test is insufficient. The useful question is whether the owned resource is released when the operation stops halfway through. Pair these checks with the Sling Model testing note when repository access sits behind a model's service dependency.

If service acquisition fails, inspect the mapping and permissions as well as component activation. The OSGi component diagnostic guide separates missing service references from failures inside an active service.

  • Verify close() on an owned resolver after both a successful read and an exception during use.
  • Verify a helper never closes a borrowed request resolver.
  • Verify login failure propagates as an operational error without attempting to close an unacquired resolver.
  • Exercise a missing resource and a denied read in integration tests; mocks cannot establish production permissions.
  • Check that returned values remain usable without retaining a resolver or session reference.

Lifecycle evidence

  • Owned resolver closes when reading succeeds.
  • Owned resolver closes when conversion throws.
  • Borrowed resolver remains open for its owner.
  • Queued work does not retain request resources.

REFERENCE DESK

Sources & further verification

Product behavior should be checked against the target AEM and search-engine release. The design choices in this note are proposed assessment criteria, not vendor guarantees.

SHARE THIS NOTE

Found this useful? Share it with someone working on AEM, platform engineering or search.

SHARE
LinkedIn X Facebook Threads

CONTINUE THE THREAD

Related engineering notes

Related engineering work