Search code examples
aemsling

Does resourceResolver.adaptTo create new object or return a cached object


I have recently come across a piece of code which is something like:

for(int i=0;i<10000;i++) { 
   ....
   PageManager manager = resourceResolver.adaptTo(PageManager.class);
   ....
}

Does it mean 10000 PageManager objects will be created or do we get the same object each time?

Thanks


Solution

  • Have a look at the Adaptable documentation hope it answer your question

    it is explicitly left as an implementation detail whether each call to this method with the same type yields the same object or a new object on each call.

    AdaptTo

    similar question purpose-of-resourceresolver-adapttosession

    Just to explain in simple

    1. The ResourceResolver is the service API which we can resolve Resource(Resources are pieces of content on which Sling act) objects.
    2. The resource resolver is available to the request processing servlet through the SlingHttpServletRequest.getResourceResolver() method. A resource resolver can also be created through the ResourceResolverFactory.
    3. A ResourceResolver is generally not thread safe! an application which uses the resolver, must provide proper synchronization to ensure no more than one thread concurrently operates against a single resolver, resource or resulting objects.
    4. The ResourceResolver is also an Adaptable to get adapters to other types.

    So when you get the resource by ResourceResolver and adaptTo other types or some representations of the object, the object will be same. Remember that the operations which you are performing on a resource (after adaptTO()) should be taken care as the resource is generally not thread safe. Example the resolver is updated to reflect the latest state by using refresh() method, etc.