【问题标题】:Calling Groovy scripts from Java and refreshing the Groovy scripts periodically从 Java 调用 Groovy 脚本并定期刷新 Groovy 脚本
【发布时间】:2014-07-07 17:07:56
【问题描述】:

我想从 Java 调用 Groovy 脚本并定期刷新 Groovy 脚本。 例如,

public class AppTest {
   public static void main(String args[]) throws Exception {
      TestVO test = new TestVO();
      AnotherInput input = new AnotherInput();
      test.setName("Maruthi");
      input.setCity("Newark");
      GroovyClassLoader loader = new GroovyClassLoader(AppTest.class.getClassLoader());
      Class groovyClass = loader.parseClass(new File("src/main/resources/groovy/MyTestGroovy.groovy"));
      GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
      Object[] inputs = {test,null};
      Map<String,String> result = (Map<String, String>)groovyObject.invokeMethod("checkInput", inputs);
      System.out.println(result);
   }
}

我的 Groovy 脚本是

class MyTestGroovy {

   def x = "Maruthi";
   def checkInput = { TestVO input,AnotherInput city ->

      if(input.getName().equals(x)) {
         input.setName("Deepan");
         println "Name changed Please check the name";
      } else {
         println "Still Maruthi Rocks";
      }

      Map<String, String> result = new HashMap<String,String>();
      result.put("Status", "Success");

      if(city != null && city.getCity().equalsIgnoreCase("Newark")) {
         result.put("requested_State", "Newark");
      }

      return result;
   }

   def executeTest = {  
      println("Test Executed");
   }
}

当我创建多个 groovy 脚本实例并执行该脚本时,我的内存管理效率如何。是否建议使用一些 Groovy 脚本作为我的自定义规则引擎。请指教。

【问题讨论】:

    标签: java grails groovy


    【解决方案1】:

    拥有同一个脚本的多个实例通常比每次创建实例时都解析类要好。性能方面,因为编译脚本需要一些时间,除了创建实例之外,您还需要付费。在内存方面,您可以更快地用完可用类的数量。即使收集了旧的类,如果您有许多脚本处于活动状态,它也可能发生......尽管这通常意味着数百甚至数千个(取决于 jvm 版本和您的内存设置)

    当然,一旦脚本更改,无论如何您都必须重新编译该类。因此,如果在您的场景中您将只有一个类的实例同时处于活动状态,并且仅在更改源之后才需要一个新实例,则您可以每次都重新编译。

    我特别提到了这一点,因为您甚至可以通过某种方式编写脚本,让您可以重用同一个实例。但这当然超出了这个问题的范围。

    【讨论】:

    • 感谢您的信息。闭包线程内的块是否安全,即当我在多线程模式下调用同一个实例并调用闭包时。闭包是否是线程安全的。提前致谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2020-03-24
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    相关资源
    最近更新 更多