Skip to main content
1-Visitor
June 19, 2023
Solved

Wrapping services into anonymous function

  • June 19, 2023
  • 1 reply
  • 941 views

Is there any benefit of wrapping whole service into anonymous function? 

eg.

 

(function() {
 const someText = 'test';
 logger.info(someText);
})();

 

 

const result = function() {
 const someText = 'test';
 
 return someText;
}();

 

I'm not sure how local variables (service scope) are managed after the service execution completes/fails. Are those variables continue to exist, even if we cannot access them? If yes, it would make sense to wrap whole service into anonymous function, so we are sure they are destroyed after function returns.

I saw this approach few times and it makes sense for me when the service returns value - we can use return statement in any place in the service, but I'm not sure about memory/security benefits.

Is there any documentation on how ThingWorx manages the cleanup and disposal of resources associated with the service execution?

Best answer by DanZ

@RD_9781013 wrote:

[...]

Is there any documentation on how ThingWorx manages the cleanup and disposal of resources associated with the service execution?


I don't think so, because this is more a task of the used Rhino JavaScript engine or at least the Garbage Collector of Java itself. My understanding is, that after a service is executed, the memory will be freed. At least that is something I observed in VisualVM when running services.

 

Outside from the fact of returning a result at any given moment, there is (to my knowledge) no other benefit for wrapping the service in a function.

1 reply

DanZ15-MoonstoneAnswer
15-Moonstone
June 19, 2023

@RD_9781013 wrote:

[...]

Is there any documentation on how ThingWorx manages the cleanup and disposal of resources associated with the service execution?


I don't think so, because this is more a task of the used Rhino JavaScript engine or at least the Garbage Collector of Java itself. My understanding is, that after a service is executed, the memory will be freed. At least that is something I observed in VisualVM when running services.

 

Outside from the fact of returning a result at any given moment, there is (to my knowledge) no other benefit for wrapping the service in a function.