Monday Nov 30, 2015

Writing a pluggable dynalink linker and using it with Nashorn

JEP-276 (JEP 276: Dynamic Linking of Language-Defined Object Models) adds a facility for linking high-level operations on objects such as "read a property", "write a property", "invoke a callable object", etc., expressed as names in INVOKEDYNAMIC call sites. Nashorn JavaScript engine in OpenJDK uses dynalink for linking script and other objects.

JEP 276 allows user written ("pluggable") linkers to be loaded via service loader mechanism. Because of Dynalink, Nashorn also allows user-written dynalink linkers to be used along from nashorn scripts! You can write your own linker(s) and drop it as a "jar" in jjs -classpath. Your scripts can make use of those pluggable linkers to handle "special linkages".

If this sounds little abstract, you may want to look at the sample dynalink linker in nashorn OpenJDK repository - This sample adds a simple DOM Element linker This linker allows scripts to access DOM child elements by child element tag name - rather than having to use DOM Java API to get child Node list and iterate to get the matching Element(s). dom_linker_gutenberg.js script uses "DOM linker". The script accesses child DOM elements by samply "_" followed by child element tag name.

You can imagine many other such useful dynalink linkers for your own Java classes or even JDK platform classes.How about a dynalink linker that supports easier access for SQL ResultSet objects - perhaps column names as properties? How about a dynalink linker that handles your domain object model complexity and exposes a simpler script access model -- without having to write any Java or script wrappers around it! All complexity is hidden in the linker code! No Java or script wrapper implies that easy script access does not result in reduced performance - because linking is just (mostly!) one time activity per callsite.

Friday Nov 27, 2015

Using Dynalink API with invokedynamic - a Java assembler example

Dynalink API JEP-276

Dynalink API ( provides a facility for linking high-level operations on objects such as "read a property", "write a property", "invoke a callable object", etc., expressed as names in INVOKEDYNAMIC call sites. Dynalink also provides a default linker for the usual semantics of these operations on plain Java objects (Java POJO "beans" linker), as well as a facility for installing your own language-specific linkers.

Dynalink has been used by Nashorn JavaScript engine internally starting from JDK 8. But, Dynalink is exposed as a public API starting from JDK 9. You can use dynalink to simplify invokedynamic generation when compiling your language for the Java platform.

To learn Dynalink API from Java code, you can check our dynalink API tests in nashorn repo. test/src/jdk/dynalink directory in Nashorn repo

There is a simple OpenJDK Java assembler based sample in nashorn repostory - $nashorn/samples/Main.asm - This example shows how "length" property can be linked using invokedynamic and dynalink. The Java beans linker that comes with Dynalink can link "length" property for Java arrays (array length) and Java Lists (List.size()). The example shows how "length" works for arrays and lists uniformly.

Wednesday Oct 28, 2015

Underscore is a keyword in Java 9, use this script to check your code!

Underscore ("_") is a keyword in Java 9. If you use "_" as an identifier, javac of JDK 8+ issues a warning. javac of JDK 9, issues an error! To check and migrate your Java code to avoid using "_" as an identifier, you can use the following Nashorn script with jjs tool. This script just parses each .java file and reports "_" variables with filename, line and column numbers. This script uses Javac Tool API and Compiler Tree API.

File: find_underscore.js
// Usage: jjs find_underscores.js -- <directory>

if (arguments.length == 0) {
    print("Usage: jjs find_underscores.js -- <directory>");

// Java types used
var File = Java.type("");
var Files = Java.type("java.nio.file.Files");
var StringArray = Java.type("java.lang.String[]");
var ToolProvider = Java.type("");
var Tree = Java.type("com.sun.source.tree.Tree");
var Trees = Java.type("com.sun.source.util.Trees");
var TreeScanner = Java.type("com.sun.source.util.TreeScanner");

function findUnderscores() {
    // get the system compiler tool
    var compiler = ToolProvider.systemJavaCompiler;
    // get standard file manager
    var fileMgr = compiler.getStandardFileManager(null, null, null);
    // Using convert script array (arguments) to a Java String[]
    var compUnits = fileMgr.getJavaFileObjects(, StringArray));
    // create a new compilation task
    var task = compiler.getTask(null, fileMgr, null, null, null, compUnits);
    var sourcePositions = Trees.instance(task).sourcePositions;
    // subclass SimpleTreeVisitor - to find underscore variable names
    var UnderscoreFinder = Java.extend(TreeScanner);

    var visitor = new UnderscoreFinder() {
        // override to capture information on current compilation unit
        visitCompilationUnit: function(compUnit, p) {
            this.compUnit = compUnit;
            this.lineMap = compUnit.lineMap;
            this.fileName =;

            return Java.super(visitor).visitCompilationUnit(compUnit, p);

        // override to check variable name
        visitVariable: function(node, p) {
            if ( == "_") {
                var pos = sourcePositions.getStartPosition(this.compUnit, node);
                var line = this.lineMap.getLineNumber(pos);
                var col = this.lineMap.getColumnNumber(pos);
                print(node + " @ " + this.fileName + ":" + line + ":" + col);

            return Java.super(visitor).visitVariable(node, p);

    for each (var cu in task.parse()) {
        cu.accept(visitor, null);

// for each ".java" file in directory (recursively).
function main(dir) {
    var totalCount = 0;
      forEach(function(p) {
          var name = p.toFile().absolutePath;
          if (name.endsWith(".java")) {

main(new File(arguments[0]));

Saturday Oct 10, 2015

Thursday Oct 08, 2015

Fun with NetLogo using Nashorn JavaScript engine

NetLogo is a multi-agent programmable modeling environment running for the Java platform. In addition to being a GUI program to edit and run NetLogo models, NetLogo supports Controlling API so that NetLogo can be invoked and controlled by a program running on JVM. The "controlling api" supports both GUI and 'headless' mode.

I used Nashorn javascript engine to use NetLogo "controlling API" from a script. I ran the bundled Maxwell's demon model in "headless mode" using the following Nashorn script:

File: nl_maxwell_demon.js

// NetLogo "controlling API" example in Nashorn

// java classes used
var HeadlessWorkspace = org.nlogo.headless.HeadlessWorkspace;
var Thread = java.lang.Thread;

// set the thread context loader for correct working of NetLogo!

Thread.currentThread().contextClassLoader = HeadlessWorkspace.class.classLoader;

// new headless workspace
var ws = HeadlessWorkspace.newInstance();

// change this as per your installation directory!
// My NetLogo installation dir is "C:\Program Files (x86)\NetLogo 5.2.1"

var NL = "C:\\Program Files (x86)\\NetLogo 5.2.1\\"; + "models\\Curricular Models\\GasLab\\GasLab Maxwells Demon.nlogo");

// setup and call "go" (100 iterations)
ws.command("repeat 100 [ go ]");

// print average left and right speeds
print("average speed (left) = " +"avg-speed-left"));
print("average speec (right) = ""avg-speed-right"));

// We're done!

I used the jjs nashorn shell command to run the above script:

$ jjs  -cp "C:\\Program Files (x86)\\NetLogo 5.2.1\\NetLogo.jar" nl_maxwell_demon.js
average speed (left) = 8.712072244000128
average speec (right) = 9.08120463863075

Saturday Oct 03, 2015

Standalone JavaFX FXML app with nashorn scripts for event handling - no java code!

In nashorn openjdk repository, there is a script called "fxmlrunner.js" in the "samples" directory. This script can accept any FXML file as command line argument and "run it". If that FXML file has event handlers written in (nashorn) javascript, then we can have complete runnable application without having to write any Java code!

When I came across this FXML example, I wanted to replace Java event handling + actual calculator implementation with nashorn scripts. The "ported" FMXL+nashorn script app. uses nashorn scripts for action handlers and uses "eval" to implement calculator back-end.

Calculator App in FXML + nashorn scripts

Download these files: Now, you can the app with the following command:

jjs -fx fxmlrunner.js -- calc.fxml

You should see a calculator app window that looks like this:

Wednesday Sep 30, 2015

Playing with Java (java9) REPL - an example that uses nashorn engine in REPL

I love "Exploratory Programming" ( tools. If you've not already played with "Java REPL" project, you may want to do so! Check out Kulla project.

Clone kulla forest @ and build using these commands:
  1. hg clone kulla-dev
  2. cd kulla-dev
  3. sh
  4. sh configure --with-boot-jdk=/path/to/jdk1.8.0
  5. make clean images
  6. make install

Once build finishes, you can use the Java REPL tool "jshell" ( $kulla-dev/build//images/jdk/bin/jshell). I built on Windows. My jshell path is D:\src\kulla-dev\build\windows-x86_64-normal-server-release\images\jdk\bin\jshell.exe.

Now, two lines to print the squares of integers in the range [0, 100):

|  Welcome to JShell -- Version 1.9.0-internal
|  Type /help for help

-> import*

-> IntStream.range(0, 100).map(x->x*x).forEach(System.out::println)

Slightly bigger repl sample that pulls weather data in JSON format, uses Nashorn script engine to parse JSON and print the statistics on it using Streams API.

File: weather.repl

import javax.script.*
import java.util.*

// URL to fetch JSON for weather data for Chennai, India
URL u = new URL(

// read text from URL
String getText(URL u) {
    StringBuilder buf = new StringBuilder();
    try (BufferedReader reader =  new BufferedReader(
        new InputStreamReader(u.openStream()))) {
    } catch (IOException exp) {
    return buf.toString();

// create nashorn engine
ScriptEngine e = new ScriptEngineManager().getEngineByName("js")

// expose weather data JSON as global variable to nashorn engine
e.put("str", getText(u))

// massage JSON using nashorn and get the max. temp values
double[] values = (double[]) e.eval(
    " val.temp.max), Java.type('double[]'))")

// stat on max. temp values

You can evaluate the above source as follows:

jshell  weather.repl
|  Welcome to JShell -- Version 1.9.0-internal
|  Type /help for help
-> DoubleSummaryStatistics{count=7, sum=227.160000, min=30.210000, average=32.451429, max=36.5800

Yep, Chennai is HOT! 32 C average! In Chennai, we have only three seasons - hot, hotter and the hottest :)

Thursday Sep 17, 2009

"helloworld" with Maxine JVM on Mac

Last night, I listened to this nice podcast on Maxine JVM from Software Engineering Radio. Maxine is a Java Virtual Machine implemented in the Java programming language.

I wanted to try out Maxine on my MacBook Pro running Mac OS X 10.5.8. I followed these steps to try it out:

  • Get the Maxine sources
        hg clone maxine
  • Setup the environment
        export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home
        export JUNIT4_CP=<full-path-of junit-4.4.jar>
  • Build Maxine
       cd $MAXINE_HOME/bin
       ./max build
       ./max image   
  • Run the "helloworld"
        ./max helloworld

Wow! Maxine VM printed "Hello World!". Now, it is time to explore Maxine's inspector and other cool stuff ...

Tuesday Jul 21, 2009

Teaching programming to kids

I've been experimenting/playing with programming tools for kids. I've two kids - 8 and 5 year old.


Great multimedia rich introduction to programming for kids. My son keeps playing with it! If you are after ease-of-use, this is probably the best choice. Available for download on Mac and Windows. If you have Squeak installed, you can get Scratch running on Linux as well (possibly with some audio problems). It is possible to export your Scratch projects as applets from your website

  • Website:
  • Tutorials:
  • Examples/Repository: Register @ to download lots of great samples! You can view scratch programs online if you have Java plugin installed.


EToys is an tool to teach children a multimedia rich authoring environment and visual programming system. If you have OLPC laptop (or emulation environment for OLPC), it comes pre-installed with EToys. Or else you can download EToys for your platform. It is avaliable for Linux, Mac and Windows.


Although StarLogoTNG is described as "tool to create and understand simulations of complex systems", it can be used as a tool to teach programming. It supports 3D and it is cross-platform a (Java) tool.


This is an environment to teach programming in a 3D environment. This is a cross-platform (Java) tool.

Turtle Art

Turtle Art activity is bundled with OLPC. If you don't have OLPC, you can use an emulator environment. For example, you can download VirtualBox and run OLPC inside it following the steps here. I run VirtualBox on Mac, Ubuntu and Windows XP.

Want to work with source code?

So far, we looked at visual programming tools. But, if you think it is better to expose to source code ("they have to look at code at somepoint anyway, let them see syntax errors sooner"), then you may want to try these:


From the site: "Greenfoot as a combination between a framework for creating two-dimensional grid assignments in Java and an integrated development environment (class browser, editor, compiler, execution, etc.) suitable for novice programmers". This is a cross-platform (Java) tool.


With Bots Inc we can learn how to program robots interactively. Language used to program is Smalltalk (BotsInc is built with Squeak). Since BotsInc is a Squeak image, it possible to slowly graduate to full Smalltalk. It is available on all platforms.

Alice 3 Beta

Alice 3 beta is hosted at Alice 3 beta seems to have support to emit NetBeans projects. I've played with Alice 3 Beta - but not yet with NetBeans project support.

Tuesday Jul 14, 2009

BTrace "unsafe" mode

We kept saying BTrace is a safe, dynamic tracing tool for Java. To ensure safety, BTrace does not permit many constructs of Java language and also allows calls only to BTraceUtils class.But, not everyone likes safety -- sometimes developers want "unsafe" facility ("I know what I am doing"-style). We have got comments of this nature about BTrace - for example here and here. We have added "unsafe" mode to BTrace - you can edit "btrace" script to change -Dcom.sun.btrace.unsafe=false to -Dcom.sun.btrace.unsafe=true. In "unsafe" mode BTrace permits all Java constructs and also allows calls to arbitrary code. Like every other unsafe facility in programming, you are on own your own with this facility! You may get weird errors while instrumenting target classes and/or running transformed code. But then you know what you are doing, right?

Monday Jul 13, 2009

javafxdoc-style docs for Java code

You may have browsed JavaFX API docs generated by javafxdoc tool. javafxdoc tool is implemented as a doclet. It is possible to use javafxdoc's doclet to generate API docs for Java code.

Note: The XMLDoclet implemented as part of javafxdoc tool is an implementation detail and not part of official JavaFX/tool API and so please do not depend on this. This is more for fun/learning/personal use!)

I generated javadoc for BTrace source using the following command:

javadoc -docletpath $JAVAFX_HOME/lib/shared/javafxdoc.jar  -doclet -sourcepath .  -subpackages com.sun.btrace

where JAVAFX_HOME is the directory where JavaFX SDK lives.

A screenshot from generated docs:

Thursday Dec 04, 2008

Playing with Alice and PhET

These days, my son is playing with these (apart from usual game sites):
Alice is a 3D programming environment. He likes it as much as he likes Scratch.
Interactive simulation tool for physical phenomena from University of Colorado. He kept trying to soft land "on the moon" :-) I guess Chandrayaan I has impressed him a lot!

What is the common between Alice and PhET apart from being great education tools? It is Java! With the advent of JavaFX, we can expect that such fantastic rich GUI applications will be written in JavaFX.

Friday Aug 08, 2008

Scriptifying BTrace?

One of the issues reported with BTrace is that the trace authors have to write "verbose" code [some people say Java is "verbose"!]. In BTrace, we have to repeat the same set of imports, annotations in every btrace file and all methods have to be "public static void" and so on. Instead of inventing a new scripting language, I've added a simple C preprocessor like step in BTrace compilation. This preprocessor is based on the one in the GlueGen project. Thanks to Ken Russell for this code and for reviewing my changes specific to BTrace project. The preprocessor solution does not rule out a scripting solution in future :-) If you have nice ideas or would like contribute in this area, you are always welcome! But, I think preprocessor solution is simple and will be useful to some.

Simple Example:


To run this sample, the following command can be used:

   btrace -I . <pid-of-the-traced-process>

Without the -I option in command line, BTrace skips the preprocessor step.

Friday Jul 25, 2008

Playing with JSqueak

Squeak is a open source implementation of Smalltalk. What is JSqueak? JSqueak is a Squeak interpreter written in Java. You can download JSqueak source code and play with it. I did the following:
  • Expanded the downloaded under a directory, say c:\\JSqueak.
  • cd c:\\JSqueak
  • javac -d . \*.java
  • copy mini.image.gz JSqueak
  • java JSqueak.Main
Even if you are not going to learn Smalltalk (why?), you can have the fun of reading Smalltalk VM implemented in Java. If you are lazy and don't want to compile, you can run directly by JNLP link from Inside the Squeak environment, I wrote the legendary "Hello World" :-) This is how it looks...

Friday Jul 18, 2008

BTrace and JMX

You can dyanamically attach BTrace to a Java process to inject trace code into it. BTrace client classescollect the trace output via a socket -- these client classes are used by BTrace command line client as well as VisualVM plugin for BTrace. How about attaching a JMX client to collect BTrace's trace data? Yes, it is possible to access a BTrace class's static fields as attributes of a MBean with this RFE.

There are two MBean samples in the BTrace repository. I attached both BTrace samples to a "Java2D demo" process. And then I attached VisualVM to view the Mbean registered by these BTrace samples:

  1. - this sample instruments java.lang.Thread.start() method to update a counter field. This counter field is accessible by JMX clients.

  2. - this sample collects histogram of java.awt.Component objects created by an application and exposes the histogram (map) as MBean attribute.




« December 2015

No bookmarks in folder


No bookmarks in folder


No bookmarks in folder