3

I'm trying to implement RPC broker. The broker takes commands, sends them to the RPC servers, waits for result and then sends the result to the client. My approach is like this pseudocode:

function onClientCommand(cmd) {
    sendCommandToRPCServer.then(function(result){
        returnResultToClient(cmd.client,result)
    })  
}  

As you can see sendCommandToRPCServer returns a promise. I'm expecting this function to be called very frequently (several thousands calls per second). When the system get under heavy load, RPC servers get slow and there will be more and more unresolved promises in Broker memory.

So my question is:

If the Broker rejects promises after some timeout, will this remove promises (e.g. its resolve and reject functions with their contexts, there is no reference to that promise) from memory? I know I can solve this by array of callbacks and periodically clear old items of it, but "promise-like" approach is better for me, because sometimes broker needs to wait for several RPC calls and then return result to client and this is easier with promises.

user2106769
  • 445
  • 5
  • 15

1 Answers1

3

No, garbage collection does not work any different for them. A function is, like any other object, garbage-collected when nothing references it any more.

There are of course some "hidden" references in the promise implementation:

  • resolving functions (resolve and reject) do reference the promise
  • the promise references all then callbacks installed on it
  • the installed handlers reference the promise created by the then() call

A good implementation does remove the reference from the resolving functions to the promise when one of them was called, and it does remove the references from the promise to the handlers when the promise was settled.

Regarding your specific use case, storing the resolving functions as callbacks while you are waiting for the respective response is perfectly fine. Have a look at this Queue implementation for an example. Just make sure to drop the functions after you used them to avoid memory leaks.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • So, it means, that if the promises will be rejected after some time-out, the memory will be eventually freed, doesn't it? – user2106769 Apr 13 '18 at 16:06
  • 1
    Yes, it should. Just make sure to free the memory where the resolving functions are stored as well. – Bergi Apr 13 '18 at 16:09