Serializing JRuby CompiledScript in Java

I have a Ruby script that I would like to run when my Java program starts.

When you tell ScriptEngine to evaluate the code for the first time, it will take some time. I get the impression that the reason it's been taking so long is because you need to compile the code first, right?

I found that you can compile Ruby code and then evaluate it later. Evaluation itself is fast — the compilation part is slow. Here I compile:

    jruby = new ScriptEngineManager().getEngineByName("jruby");

    Compilable compilingEngine = (Compilable)jruby;

    String code = "print 'HELLO!'";

    CompiledScript script;
    script = compilingEngine.compile(code);

This fragment takes some time. Later, when you rate it, that's fine.

So, I was wondering if it is possible to “save” this compiled code to a file, so in the future I will be able to “download” it and just execute it without compiling again.

+4
3

, CompiledScript. JRuby . jrubyc - Ruby script Java, :

jrubyc <scriptname.rb>

scriptname.class. , (String [] argv) ( : jruby ), , , .

jrubyc : https://github.com/jruby/jruby/wiki/JRubyCompiler#methods-in-output-class-file

+4

, :

class CompiledScriptCache {

    static {
         CompiledScriptCache INSTANCE = new CompiledScritCache();
    }

    publich static CompiledScriptCache get(){
        retrun INSTANCE;
    };

    List<CompiledScript> scripts = new ArrayList<>();

    public CompiledScript get(int id){
        return scripts.get(id);
    }

    public int add(String code){

        ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");

        Compilable compilingEngine = (Compilable)jruby;

        CompiledScript script;
        script = compilingEngine.compile(code);
        scripts.add(script);
        return scripts.size()-1;

    }


}

, , .

, , - Java- -:

https://github.com/jruby/jruby/wiki/GeneratingJavaClasses

+2

this, no.

" , , , , , ".

+2

Source: https://habr.com/ru/post/1539853/


All Articles