caoccao/Javet

Why would it cause a breakdown

Closed this issue · 2 comments

    public static void main(String[] args) throws JavetException {
        V8Runtime v8Runtime = V8Host.getNodeInstance().createV8Runtime();
        Container container = new Container();
        container.put("printer", wrapAsObject(v8Runtime, new Printer()));
        v8Runtime.getGlobalObject().set("container", wrapAsObject(v8Runtime, container));
        v8Runtime.getExecutor("""
               const p1 = container.get('printer')
               console.log(p1)
               const p2 = container.get('printer')
               console.log(p2)
                """).execute();
    }
    public static class Printer {
        @V8Function(thisObjectRequired = true)
        public void print(V8Value thiz, V8Value... values) {
            System.out.println(Arrays.toString(values));
        }
    }

    public static class Container {
        private Map<String, V8Value> map = new HashMap();
        public void put(String key, V8Value v8Value) {
            map.put(key, v8Value);
        }

        @V8Function(thisObjectRequired = true)
        public V8Value get(V8Value thiz, String key) {
            V8Value v8Value = map.get(key);
            return v8Value == null ? thiz.getV8Runtime().createV8ValueUndefined() : v8Value;
        }
    }

    public static V8Value wrapAsObject(V8Runtime v8Runtime, Object object) throws JavetException {
        V8ValueObject v8ValueObject = v8Runtime.createV8ValueObject();
        v8ValueObject.bind(object);
        return v8ValueObject;
    }

Why would it directly cause a breakdown
Container. get ('printer ') If executed once, it will not work; if executed again, it will crash

The V8 values you put in the map have been closed by Javet because their lifecycle is managed by Javet. Calling a closed V8 value results in core dump immediately.

In this case, you may call toClone() to get an instance of the V8 value whose lifecycle is managed by you. That needs to be applied to both get() and set().

您在地图中放置的 V8 值已被 Javet 关闭,因为它们的生命周期由 Javet 管理。调用关闭的 V8 值会立即导致核心转储。

在这种情况下,您可以调用以获取 V8 值的实例,其生命周期由您管理。这需要同时应用于 和 。toClone()``get()``set()

Thank you for your answer. The problem has been resolved