ResourceResolver try-with-resources in AEM 6.2

Avatar

Avatar

Gdubz-57m2mu

Avatar

Gdubz-57m2mu

Gdubz-57m2mu

27-01-2017

Based on the versions I've found, it should work but I just wanted to confirm if anyone has used/tested this with any luck, without leaving tons of sessions open all over the place.

According to SLING-4805[1], ResourceResolver should properly extend AutoCloseable[2] as of Sling API 2.11.0. And according to the bundle I'm seeing in my system console of my local AEM 6.2 instance, it's using Sling API 2.11.0. So I should be able to refactor all of our try-catch-finally resource resolver code to try-with-resources[3], yeah?

try (ResourceResolver resolver = resourceResolverFactory.getServiceResourceResolver(null)) { // do something with the resolver } catch (LoginException e) { // error handle }

Probably just being paranoid and second guessing myself, wondering if anyone else has tried this.

[1] https://issues.apache.org/jira/browse/SLING-4805
[2] https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html
[3] https://docs.oracle.com/javase/8/docs/technotes/guides/language/try-with-resources.html

View Entire Topic

Avatar

Avatar

Gdubz-57m2mu

Avatar

Gdubz-57m2mu

Gdubz-57m2mu

30-01-2017

smacdonald2008 wrote...

Most ppl that is speak with about this manually close sessions. Have you tried this API? 

 

We have historically done something like the following code, albeit with the getting/closing abstracted away to util class methods:

String serviceName = “some-service-name”; ResourceResolver serviceResolver = null; try { Map<String, Object> serviceParams = new HashMap<>(); serviceParams.put(ResourceResolverFactory.SUBSERVICE, serviceName); serviceResolver = resolverFactory.getServiceResourceResolver(serviceParams); // do whatever is needed with the resolver here } catch (LoginException e) { LOG.error("Error getting service resolver for \"{}\": {}", serviceName, e); } finally { Session session = serviceResolver.adaptTo(Session.class); if (session != null) { session.logout(); session = null; } if (serviceResolver != null) { if (serviceResolver.isLive()) { serviceResolver.close(); } serviceResolver = null; } }

Just thought we could simplify our code a bit by not having to deal with the finally block.

To answer your question, yes I just tried it out on Friday and it's error free, but that doesn't necessarily mean that it's closing properly. I suppose I could try to fetch some resources with it after the try-with-resources block and see if it's still open... 

After having memory leak problems with CQ 5.5 and 5.6.1 because of unclosed sessions, I'm just a bit paranoid, I guess.