Skip to content

Commit

Permalink
node-api: run finalizers directly from GC
Browse files Browse the repository at this point in the history
PR-URL: #42651
Reviewed-By: Gabriel Schulhof <[email protected]>
Reviewed-By: Michael Dawson <[email protected]>
  • Loading branch information
vmoroz authored and targos committed Nov 27, 2023
1 parent edef4fa commit 5148f03
Show file tree
Hide file tree
Showing 10 changed files with 477 additions and 40 deletions.
36 changes: 36 additions & 0 deletions doc/api/n-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5420,6 +5420,42 @@ invocation. If it is deleted before then, then the finalize callback may never
be invoked. Therefore, when obtaining a reference a finalize callback is also
required in order to enable correct disposal of the reference.

#### `node_api_post_finalizer`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status node_api_post_finalizer(napi_env env,
napi_finalize finalize_cb,
void* finalize_data,
void* finalize_hint);
```

* `[in] env`: The environment that the API is invoked under.
* `[in] finalize_cb`: Native callback that will be used to free the
native data when the JavaScript object has been garbage-collected.
[`napi_finalize`][] provides more details.
* `[in] finalize_data`: Optional data to be passed to `finalize_cb`.
* `[in] finalize_hint`: Optional contextual hint that is passed to the
finalize callback.

Returns `napi_ok` if the API succeeded.

Schedules a `napi_finalize` callback to be called asynchronously in the
event loop.

Normally, finalizers are called while the GC (garbage collector) collects
objects. At that point calling any Node-API that may cause changes in the GC
state will be disabled and will crash Node.js.

`node_api_post_finalizer` helps to work around this limitation by allowing the
add-on to defer calls to such Node-APIs to a point in time outside of the GC
finalization.

## Simple asynchronous operations

Addon modules often need to leverage async helpers from libuv as part of their
Expand Down
10 changes: 10 additions & 0 deletions src/js_native_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,16 @@ NAPI_EXTERN napi_status NAPI_CDECL napi_add_finalizer(napi_env env,

#endif // NAPI_VERSION >= 5

#ifdef NAPI_EXPERIMENTAL

NAPI_EXTERN napi_status NAPI_CDECL
node_api_post_finalizer(napi_env env,
napi_finalize finalize_cb,
void* finalize_data,
void* finalize_hint);

#endif // NAPI_EXPERIMENTAL

#if NAPI_VERSION >= 6

// BigInt
Expand Down
Loading

0 comments on commit 5148f03

Please sign in to comment.