nodejs / nodejs/node-addon-api

Supporting circular references that can be garbage collected.

Open
#1,665 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

never-stale
Dominant language
C++
Stars
2.4k
Forks
499
Avg merge
2d 11h
Merged PRs (30d)
2

Description

In JavaScript I can make two objects that reference each other and they'll still be GCed.

function makeObjectsThatReferenceEachOtherButLeakNoReferences() {
  const a = new Uint8Array(1024);
  const b = new Uint8Array(1024);
  a.other = b; // make them reference each other
  b.other = a;
}

makeObjectsThatReferenceEachOtherButLeakNoReferences();

In the code above, even though a circular reference was created, JavaScript will see there is no path from root and garbage collect the objects.

Is it possible to do the same in C++ Napi. If I make a class

class MyClass : public Napi::ObjectWrap<MyClass> {
  ...
  Napi::Reference<Napi::Object> storedObjectRef_;
};

And I manage to make 2 instanced of MyClass and set storedObjectRef_ so they point to each other, AFAICT these objects will never be garbage collected.

Is there a solution?

Note: I know I could add some function close or whatever to null out storedObjectRef_ but that's not really the question I'm asking. I'm trying to reproduce JS garbage collecting circular references.

One idea I guess, which appears to work, is I could add a JS property to MyClass. So instead of Napi::Reference<Napi::Object> storageObjectRef_ I'd use Get, Set as in

this->Value().Set("storageObjectRef", otherObject);

but unfortunately that's visible externally which I don't want. I could use a symbol but those are inspectable too. Though it might be better than nothing if there is no other solutions.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Napi::ObjectWrap and Napi::Reference usage shown in the issue, then investigate how Node-API handles native references and garbage collection for mutually referencing objects. Done means establishing whether collectible circular references are supported and documenting or proposing the required API-level approach; the issue does not name a source file or test.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, nodejs
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.