My node/javascript program receives lots of messages. Each time a message is received I create a new object, passing it message content. Within the new objects constructor, the object does a bunch of stuff, including some mongo operations with callbacks.
When the operations that are performed within the object constructor are complete, the object is no longer needed or wanted.
After some experiments involving complexity (i.e. storage of the object in an array element or as a property of a 'master' object and then deleting it, I tried the simple approach.
var x = new DisposableObject(message);
delete x;
This seems to work fine. There may be many instances of DisposableObject in existence at any time. DisposableObject is created and does everything expected of it in tests. I am assuming that when I delete 'x' that this does not affect the object itself, just the reference to it that is contained in 'x'. The objects callbacks occur and all is good.
So four questions:
- Will this simple mechanism allow the garbage collector (node/V8) to get rid of the object?
- Is there some awful trap door awaiting my code because I am doing this?
- Is there any issue with multiple instances of DisposableObject floating around waiting for callbacks when there is no active reference left to them in my program?
- Is there a better way to create the objects, then make sure they can be garbage collected after all their operations are completed?