Highly Efficient Java & JavaScript Integration

Highly Efficient Java & JavaScript Integration

Over the past 4 months I’ve been working on integrating Java and JavaScript in a highly efficient manner. Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:

  • Neither support ‚Primitives‚. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean.
  • Nashorn is not supported on Android.
  • Rhino compiler optimizations are not supported on Android.
  • Neither engines support remote debugging on Android.

To help address these issues, I’ve built a new JavaScript runtime for Java based on Google’s JavaScript Engine, V8. The runtime, called J2V8, is open sourced under the EPL and available on GitHub. I’ve been running it on MacOS, Linux and Android.

Unlike other JS Runtimes (including JV8, Jav8), J2V8 takes a primitive based approach, resulting in much less garbage. The following script produces an array containing the first 100 fibonacci numbers. Each of these numbers can be accessed directly, without the need for wrapper objects. Executing this script 10,000 times on Rhino takes 7.5 seconds. The same script runs 10,000 times on J2V8 in under 1 second.

<pre lang="JavaScript">var i;
var fib = []; //Initialize array!

fib[0] = 1;
fib[1] = 1;
for(i=2; i<=100; i++)
{
    fib[i] = fib[i-2] + fib[i-1];
}
fib;</pre>

Fibonacci in JavaScript

<pre lang="Java">V8Array array = v8.executeArrayScript(script);
double total = 0;
for (int i = 0; i < 100; i++) {
  total += array.getDouble(i);
}
System.out.println(total);
array.release();</pre>

Accessing JS Arrays in Java

The runtime was built by exposing parts of the V8 API through a thin JNI bridge. This approach allows you to embed V8 directly into Java applications without the use of C/C++. J2v8 currently targets V8 version 3.26, but I’ll be updating that to a more recent build soon.

The runtime currently supports V8Objects, V8Arrays, invoking scripts, calling JS functions from Java and registering Java Functions as callbacks from JS. There is also a small library for converting V8Objects and V8Arrays to Java Maps and Lists. Finally, the runtime supports remote debugging and can be utilized with tools such as Chrome Developer Tools for Eclipse.

Screen Shot 2014-11-14 at 2.41.40 PM
Over the next few weeks I’ll be publishing builds and putting together a getting started guide. If you are interested in this project, please let me know or ping me on twitter.

8 Comments

Sorry, the comment form is closed at this time.