Saturday, January 25, 2014

Introduction to Nashorn

Nashorn (pronounced naz-horn) is the Javacript engine for the JVM that will be shipped with JDK8. It's a written using 100% Java, is highly optimized and is InvokeDynamic based. Javascript code is converted into bytecode by Nashorn so that it will run on the JVM.

What does that mean?

It means that Nashorn provides complete interoperablity between JavaScript and Java worlds. i.e JavaScript code can directly call Java code, and vice versa. Nashorn also lets you create and manipulate Java objects, extend Java classes and implement Java interfaces. This interoperability also gives access to many additional tools and libraries and gives you the best of both worlds.

Why Javascript?

Javascript as been really taking off along with the popularity of HTML5. Loads of libraries are being introduced every day and there are many Javascript developers out there as well. In fact, stats in 2013 show that there are almost as many Javascript developers as there are Java developers. Turns out Javascript it no longer 'just a' scripting language that is only used for front end development on browsers. :)

How do you start using Nashorn?

You have two options

  • Command Line with jjs
  Set your environment variables to point to your JDK8 installation. (you can get an early access release from here.
  Open up your cmd line and enter jjs
~>jjs
 jjs> print("Hello World");
 
  •  Embed in Java code and use javax.script api
 ScriptEngineManager m = new ScriptEngineManager();
 ScriptEngine e = m.getEngineByName("nashorn");
   
 try {
     e.eval("print('Hello World')");
 } catch (ScriptException e1) {
     e1.printStackTrace();
 }



Examples

Calling Java methods 
As you can see you may treat Java objects just like javascript objects. (Which is achived through InvokeDynamic - which I will come to later)

Java arrays can be created as follows

Collections are interpreted as arrays

Here we are subclassing the abstract TimerTask class.

And since this is really javascript, we can directly pass in the function as a Lambda.

Similarly, functionality can be directly passed into a new thread (again as a Lambda)


Nashorn also integrates well with JavaFX. See this for a pretty cool demo. Just run it with jjs -fx -scripting fireworks.js


InvokeDynamic and Dynalink

This is what enables languages on the JVM to talk to each other. When you make a call, the Dynalink library (using the invokeDynamic instruction) determines at run time if it's a call to a JavaScript function,  Java function or a function of any other JVM language.


No comments:

Post a Comment