简体   繁体   中英

Running and optimizing Groovy Scripts dynamic execution in Java application

I have been exploring methods of dynamically running groovy scripts in the java application.

I've gone through methods like: 1. Groovy Shell

binding.setVariable("x", 5);
String script = "y = x * x"
GroovyShell gs = new GroovyShell();
Script script = gs.parse(script);
script.run();
  1. Using GroovyClassLoader.

There are two java applications that I have. One of them is a backend for the GUI that stores data while the executes it. There's no common cache between the two. In order to avoid the overhead of compilation everytime, I am considering to compile the application first in the application B, and then cache it (so it avoids memory leak as well). Also, I tried storing the class files generated by compiling the script initially and then storing it in the database in form of bytes but haven't had any success with it till now.

However, I am not sure if this would be an optimization or if the Groovy Shell/ Groovy Class Loader already caches generated class files. What should be the best way to go about it?

Also, the scripts are not anticipated to be simple, so which mechanism would be better one here Groovy Shell or the Groovy Class Loader? (Also, exploring GrooyScriptEngine, but it seems it won't be needed for simple scripts).

Afaik gs.parse(script) will not cache the compilation. Thus caching the Script would help, since you then do not have to pay for the compilation each time. If you really want to write the bytecode into a database, then I suggest to go with GroovyClassLoader (GCL)... In fact I suggest to subclass it and override createCollector to provide your own collector (delegating to the original collector), which allows you to access the byte[]. Or you go with a BytecodeProcessor , which you have to set in the CompilerConfiguration you give to your GCL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM