History of Embedding JavaScript in Java Applications

History is useful to learn from others’ experiences and observations. In this post, we’ll see some history and evolution of JavaScript implementation in JVM.

If you search the web for “javascript in jvm”, you’ll probably see results talking about 2 projects – GraalJS and Nashorn. But, Javascript in JVM didn’t start with Nashorn.

Rhino

Originally, the need for running JavaScript in JVM arose when Netscape planned to write their next version of “Navigator” (Internet Browser) using Java in 1997.

Though Netscape later stopped their Java-based navigator project, a couple of companies—notably Sun (the company that created the Java programming language) (now Oracle)—paid for a license to use it and include Rhino in their products. Rhino was originally designed to compile all Javascript code to Java bytecode and generate class files. This produced a good performance, but the time it takes to compile and effective memory leak as Java doesn’t garbage collect the strings interned and classes generated but not used anymore.

In 1998, Rhino added “interpreted” mode. Over the years, with JSR-292 and JSR-223 making the API for embedding scripting in Java relatively easy, the Javascript-only engine Rhino started losing some of its market share. It’s still alive, but not the main contender in this space anymore.

Nashorn

Until Java SE 7, Oracle was shipping Rhino, as noted above. From the SE 8 version, Java came with Nashorn, based on JSR-292 and JSR-223. Nashorn started supporting ECMA-normalized Javascript specifications and better performance in runtime through the “invokedynamic” call site usage. Though Nashorn achieved 100% pass rate on the ECMAScript 5.1 test suite, Oracle cited challenges in maintenance and deprecated the Nashorn project with the release of Java 11. After getting removed from the official Java build, Nashorn continues as a standalone OpenJDK project in GitHub.

GraalVM / GraalJS

Graal VM has its roots in the Maxine VM project at Sun Microsystems (now Oracle), which uses a meta-circular development approach. Graal VM aimed to write a Java virtual machine using the same meta-circular approach to avoid issues in developing and maintaining a C++ codebase, particularly due to manual memory management required by C++.

GraalVM is trying to address various aspects of Java applications – startup time, compiling ahead of time for a target platform (also known as native image), and supporting guest languages in a JVM-host application based on the Truffle framework. JavaScript as a guest language is supported in GraalVM through the GraalJS project.

GraalVM can be run as JVM with your application classes loaded through which the embedded Javascript can be executed in ‘interpreted’ mode or ‘compiled’ for better performance.

Stay tuned for more updates on how Polyglot programing evolves with GraalVM and how to use GraalJs in production with scale and optimal performance.