Using Lisp or Scheme for runtime configuration of Java programs

后端 未结 4 1326
梦毁少年i
梦毁少年i 2021-02-05 22:59

I have now seen several projects ending at a point where the actual configuration depended on things only available at run-time.

The typical way to configure a Java prog

4条回答
  •  既然无缘
    2021-02-05 23:37

    I know you want a small size and runtime. Scheme is the usual choice for easy embedding, and would be my first choice. But I have no information on that field, though. My second choice is Clojure:

    • Not that small; the jar is ~3 MB
    • Overkill for a simple config reading, but the extra features can be safely ignored
    • ~ Easy to call from Java: Calling clojure from java
    • Full, excellent access to JVM
    • Might invoke a small extra to the startup, which can be too much (see below)
    • Now that I tried replicating the example's functionality with Clojure, I feel that Clojure isn't well suited for these kind of scripts (rc, etc). Clojure 1.3 will address some of that startup penalty but I don't know the magnitude of speed improvements coming

    A respective code with using Clojure:

    import clojure.lang.RT;
    import clojure.lang.Var;
    import clojure.lang.Compiler;
    import java.io.FileReader;
    import java.io.FileNotFoundException;
    
    public class ClojTest {
        public static void main(String[] args) throws Exception {
            try {
                Compiler.load(new FileReader("hello.clj"));
            } catch(FileNotFoundException e) { return; }
    
            System.out.println("Message: '"+ RT.var("user", "msg").get() +"'");
    
            // Values
            int answer = (Integer) RT.var("user", "answer").get();
    
            // Function calls
            System.out.println(RT.var("user", "countdown").invoke(42));
        }
    }
    

    with hello.clj being:

    (ns user)
    (defn countdown [n]
      (reduce + (range 1 (inc n))))
    
    (def msg "Hello from Clojure!")
    (def answer (countdown 42))
    

    Running time java ClojTest for a while yields in an average of 0.75 seconds. Clojure compiling the script has quite a penalty!

提交回复
热议问题