javaandroidjava-native-interfacev8libv8

v8 on a background thread in Android JNI


I am trying to call v8 from a JNI call in an android application from a background thread. It is causing a runtime crash with a complaint about v8::ObjectTemplate::New(v8::Handle

to reproduce call the following jni

    void JSfunc() {
        v8::Isolate* currentIsolate = v8::Isolate::GetCurrent();
        if(!currentIsolate) {
            currentIsolate = v8::Isolate::New();
        }
        v8::HandleScope handle_scope(currentIsolate);
        v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
    }

from the following Java code

    {
    final Thread loadJS = new Thread() {
        @Override
        public void run() {
            JSfunc());
        }
    };
    loadJS.start();
    }

If you call the function directly from the UI thread or a runnable it works.

Any ideas?


Solution

  • The problem is that the code to generate an Isolate is missing

    currentIsolate->Enter();
    

    so the correct JNI function is

    void JSfunc() {
        v8::Isolate* currentIsolate = v8::Isolate::GetCurrent();
        if(!currentIsolate) {
            currentIsolate = v8::Isolate::New();
            currentIsolate->Enter();
        }
        v8::HandleScope handle_scope(currentIsolate);
        v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
    }