Handle Scope

    To handle this case, JerryScript HandleScope extension provides the ability to establish a new ‘scope’ to which newly created handles will be associated. Once those handles are no longer required, the scope can be ‘closed’ and any handles associated with the scope are invalidated. The methods available to open/close scopes are and jerryx_close_handle_scope.

    JerryScript only supports a single nested hierarchy of scopes. There is only one active scope at any time, and all new handles will be associated with that scope while it is active. Scopes must be closed in the reverse order from which they are opened. In addition, all scopes created within a native method must be closed before returning from that method.

    Summary

    It is necessary in common cases that a handle has to be promote to outer scope and prevent from been garbage collected. To handle this case, a escapable handle scope has been proposed from which one object can be promoted to the outer scope. The method available to escape an object from been release at current scope is jerryx_escape_handle.

    1. #include "jerryscript.h"
    2. #include "jerryscript-ext/handle-scope.h"
    3. static jerry_value_t
    4. create_object (void)
    5. {
    6. jerryx_escapable_handle_scope scope;
    7. jerryx_open_escapable_handle_scope (&scope);
    8. jerry_value_t obj = jerryx_create_handle (jerry_create_object ());
    9. jerry_value_t escaped_obj;
    10. jerryx_close_handle_scope (scope);
    11. // escaped_obj has now been escaped to outer scope, thus not released at this point
    12. return escaped_obj;
    13. } /* create_object */
    14. static void
    15. test_handle_scope_val (void)
    16. {
    17. jerryx_handle_scope scope;
    18. jerryx_open_handle_scope (&scope);
    19. jerry_value_t obj = create_object ();
    20. } /* test_handle_scope_val */
    21. int
    22. main (void)
    23. {
    24. jerry_init (JERRY_INIT_EMPTY);
    25. test_handle_scope_val ();
    26. jerry_gc (JERRY_GC_PRESSURE_LOW);
    27. jerry_cleanup ();
    28. } /* main */

    See also

    To prevent trapping into system calls frequently, a pre-allocated dedicated list mechanism has been introduced to the implementation of JerryX handle scope.