Saturday, February 12, 2011

POSIX for Java

I've long felt that Java sorely lacks for not having a standard POSIX interface. Every significant platform that the full version of Java runs on has POSIX, so it's no loss in portability to outright support it. Yet, the lack of POSIX support can really hurt applications that want to do something like scripting. Developers on the ground are left using crummy hacked-together scripting languages just because they provide POSIXY things, most especially process control. Process control is key because once you have good process control, you can shell out for the rest.

I'm over three years late to notice it, but JRuby has an excellent solution to this problem:
So the idea behind JNA ( is to use a foreign function interface library (libffi in this case) to wire up C libraries programmatically. This allows loading a library, inspecting its contents, and providing interfaces for those functions at runtime. They get bound to the appropriate places in the Java interface implementation, and JNA does some magic under the covers to handle converting types around. And so far, it appears to do an outstanding job.

With this code in JRuby, we now have fully complete chmod and chown functionality. Before, we had to either shell out for chmod or use Java 6 APIs that wouldn't allow setting group bits, and we always had to shell out for chown because there's no Java API for it. Now, both work *flawlessly*.

I wonder how this is working out in practice? I wonder if anyone's tried it for Scala? I wonder if Oracle will adopt it into the Java mainline?

Interestingly, Squeak went through a similar history with its own native method interface. The initial version marked native methods with an integer index, and that index was looked up in a table of function pointers inside the VM. The next iteration was like JNI, and because it named native methods with strings, you could link in new ones with shared libraries. After that came an iteration much like JNA, called FFI. Like JNA, Squeak's FFI lets you access existing library directly without needing to write any glue code beyond a specification of the type signature of what you're calling.

The main differences for the Squeak version of this history are (1) they did it years earlier (2003 versus 2007), and (2) the platform maintainers immediately adopted it as a core feature. It would be great if Java could adopt the same thing as a core feature. Is there even a JSR for it, though? My initial Google searches aren't turning anything up.

No comments: