Graphviz with Java
During my experiments with the maven dependency browser I found it a pity that Graphviz is a native library and not available as a Java package.
This means, it has to be installed on a machine manually before it can be used from Java. What’s more, to generate a graphic, one has to create a string containing the diagram in dot format and send this string to a Graphviz process. Not very user friendly.
Googling around, I found this project. It’s a transformation of the Graphviz C code into Javascript, using the very cool Emscripten. I tried it in a browser and it worked like a charm. Great.
Then, I tried to run it on Java 7’s Rhino Javascript engine. It didn’t work because of some spurious syntax errors. (It didn’t like that a function is called continue
.) I know that Rhino is not perfectly standard compliant, so I gave up.
Java 8 has a brand new Javascript engine named Nashorn. And indeed, the german animal could understand the 3 MB of javascript code and produced a nice little graphic. It was pretty slow but it worked. Yay.
Next thing was to create a nice API to create an object model of a graph instead of using plain strings. Some hours later, a first version of it was ready and I created some nice graphics.
Playing around with the API, it became more and more painful that the generation process was really slow. Initializing the engine took around 20s and then generating a graphic was also a thing of seconds.
In my favorite inspiration situation (taking a shower), I remembered that I saw a talk about using Google’s V8 Javascript engine in Java. The project is called J2V8. Again, the beast run straightaway. And it was blazingly fast compared to the gemütlich Nashorn.
I made some quick performance comparison and there are the results:
V8 is one to three orders of magnitude faster than Nashorn. Typical delays are in the milliseconds range, not seconds. The Java engine is probably not that bad, but V8 is simply incredibly fast.
Thanks to it, the whole project is perfectly usable. And my weekend was not spent totally in vain. Standing on the shoulders of the giants Graphviz, Emscripten and V8, it was possible to achieve something useful in very little time. The project is on GitHub as well as in Maven central.
Have fun!