11

Every now and then I think it would be nice to use clojure for shell scripts, but a startup time of about 900ms is way too slow. I'd then googlestartpage for "nailgun clojure", but the only results that show up are for special cases like vimclojure. That's when I, pretending not to have time, turn to more awkward languages that start up faster.

So, how can nailgun be used to speed up the startup time of clojure?

Evgeniy Berezovsky
  • 18,571
  • 13
  • 82
  • 156

1 Answers1

22

Debian

Do the following once:

apt-get install nailgun                          # install nailgun
java -server -jar /usr/share/java/nailgun.jar&   # run nailgun server
ng-nailgun ng-cp /usr/share/java/clojure-1.4.jar # add clj to classpath

Now that the server is running and configured, you can run your clojure scripts on it:

ng-nailgun clojure.main path/to/myscript.clj

In my case, startup time of the actual script went down to 80ms, compared to 900ms without nailgun.

To make running the actual script more convenient, create an executable file ng-clojure containing the following line, and put it somewhere in your path:

ng-nailgun clojure.main "$@"

In your clojure shell script, add this as the first line:

#!/usr/bin/env ng-clojure

Then make the clojure shell script executable and run it like

path/to/myscript.clj

OSX

brew install nailgun
ng-server 
ng ng-cp ~/.m2/repository/org/clojure/clojure/1.5.1/clojure-1.5.1.jar 

Then execute your script as above.

Update: Having used it for a while, it doesn't seem to work flawlessly. Sometimes I'm getting random errors that don't occur when running without nailgun, and sometimes there seems to be a memory leak that makes the nailgun JVM consume all memory over time, eventually making the system swap to disk. Haven't memory profiled this yet, but wanted to add this heads-up.

Evgeniy Berezovsky
  • 18,571
  • 13
  • 82
  • 156
  • Massive! Someone should share this on a Planet Clojure blog. – mike3996 Oct 01 '13 at 16:54
  • Wouldn't get problems with code clashes when trying to run different things on one java server? Or have I misunderstood something? – rvirding Oct 04 '13 at 01:42
  • @rvirding I'm not sure what you mean by "code clashes", but I wouldn't be surprised if this didn't work 100%. There might for example be issues with things like static global state. – Evgeniy Berezovsky Oct 07 '13 at 01:10
  • The likely cause of the memory leak is that Clojure will generate many new classes at runtime, and the jvm's gc is not as adept with cleaning up permgen / garbage classes as it is with normal data – noisesmith Mar 20 '15 at 00:44
  • @noisesmith It's a while back now, but I'd be surprised if I had, during the lifetime of nailgun, created what amounts to gigabytes of class files - garbage collected or not. – Evgeniy Berezovsky Mar 20 '15 at 01:10