Groovy中GC大坑见证代码

使用groovy动态编译类、script时,经常会有gc溢出问题。其原因之一就是groovy把每次编译的文件或String做了缓存,而字符串的处理最易引发问题。位于于GroovyClassLoader.java类中,其代码如下:

每次groovy编译脚本后,都会缓存该脚本的Class对象,下次编译该脚本时,会优先从缓存中读取,这样节省掉编译的时间。这个缓存的Map由GroovyClassLoader持有,key是脚本的类名,而脚本的类名在不同的编译场景下(从文件读取脚本/从流读取脚本/从字符串读取脚本)其规则不同,当传入text时,class对象的命名规则为:

"script" + System.currentTimeMillis() + Math.abs(text.hashCode()) + ".groovy"

因此,每次编译的对象名都不同,都会在中添加一个class对象,导致class对象不可释放,随着次数的增加,编译的class对象将PERM区撑满。

注意:以下代码是必然把内存撑爆的:

        GroovyShell shell = new GroovyShell();
		String scriptText = "def mul(x, y) { x * y }\n println mul(5, 7)";
		while (true) {
		    Script script = shell.parse(scriptText);
		    Object result = script.run();
		}

 

而这段代码才是正解:

        while (true) {
			GroovyShell shell = new GroovyShell();
			String scriptText = "def mul(x, y) { x * y }\n println mul(5, 7)";
			Script script = shell.parse(scriptText);
			Object result = script.run();
		}

这是因为再多的GroovyShell,在gc时都可以被收掉,而其中容纳的Class也会随之消亡。

把GroovyShell换成GroovyClassLoader也是一样的用法。

转载于:https://my.oschina.net/showapi/blog/1634274

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值