惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
NISL@THU
NISL@THU
T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
Cyberwarzone
Cyberwarzone
D
Docker
The Hacker News
The Hacker News
C
CERT Recently Published Vulnerability Notes
Vercel News
Vercel News
Project Zero
Project Zero
S
Schneier on Security
aimingoo的专栏
aimingoo的专栏
I
Intezer
腾讯CDC
M
MIT News - Artificial intelligence
Hugging Face - Blog
Hugging Face - Blog
P
Palo Alto Networks Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
AWS News Blog
AWS News Blog
GbyAI
GbyAI
MongoDB | Blog
MongoDB | Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Vulnerabilities – Threatpost
G
Google Developers Blog
N
Netflix TechBlog - Medium
The Cloudflare Blog
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
A
Arctic Wolf
S
Securelist
酷 壳 – CoolShell
酷 壳 – CoolShell
Cisco Talos Blog
Cisco Talos Blog
Recent Announcements
Recent Announcements
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 热门话题
T
Threatpost
Latest news
Latest news
Blog — PlanetScale
Blog — PlanetScale
Security Latest
Security Latest
Engineering at Meta
Engineering at Meta
大猫的无限游戏
大猫的无限游戏
H
Help Net Security
The GitHub Blog
The GitHub Blog
T
Tor Project blog
P
Proofpoint News Feed

祈雨的笔记

安全多方计算MPC spark原理解析 kueue执行源码分析 spark on k8s执行源码分析 spark-operator源码解析 系统压测遇到的缓存击穿问题 我的世界PC与安卓联机 蚂蚁金服流量投放平台的AIG改造 G1大对象致Old区占用率高 日志打印导致接口响应率下跌分析 ERROR日志打印导致CPU满载 记OceanBase死锁超时 应用发版期间服务响应超时 Ark Serverless初探 系统优化复盘一二三 The user specified as a definer does not exist Kong网关初探 API网关选型调研 CPU火焰图常用工具 配置中心选型调研 root操作Nginx导致用户组错误 基于Proxifier使用代理 FastJSON字段智能匹配踩坑 Nacos初探 记一次Nginx服务器CPU满荷载故障 基于券系统分库分表的思考 limit不参与SQL成本计算致索引失效 Linux常用性能监控命令 golang低版本http2偶现400 hostname in certificate didn't match 常见对称加密原理以及应用 tcp_tw_recycle引起的TCP握手失败 记一次mysql执行DDL导致锁表 mysql磁盘占用查看 mysql对text字段update致磁盘增长 elasticsearch报错index read-only TIME_WAIT与Http的Keep-Alive 记一次TIME_WAIT导致连接数报警 记一次生产事故OOM问题排查 redis分布式锁RedissonLock的实现细节 webservice复杂加密签名(2)java调用 webservice复杂加密签名(1)SoapUI mysql延时关联 利用中间人拦截实现APP内H5窜改 MySQL表字符集不同导致关联查询索引失效 通过SSH隧道远程办公 数据落盘方案 BeanDefinitionRegistryPostProcessor扩展 mysql空间索引 HTTPS攻击 spring循环依赖过程解析 elasticsearch性能优化 mysql IS NULL 使用索引 mysql字符集utf8mb4失效踩坑 常用加密算法 xml与javaBean转换 初探InnoDB MVCC源码实现 mysql索引原理 redis之list源码分析 redis之key过期源码分析 redis之string源码分析 redis之hash源码分析 线程池之ThreadPoolExecutor mysql数据页结构 Using temporary与Using filesort mysql回表致索引失效 springboot(28)HTTP连接池 定时任务之ScheduledThreadPoolExecutor elasticsearch常用script聚合 elasticsearch实现like查询 elasticsearch实现乐观锁 elasticsearch准实时原理 springboot(27)自定义缓存读写机制CachingConfigurerSupport optimizer tracing arthas常用命令 HTTP和HTTPS详解 redis集群选举机制 kafka消息重试 一点压力测试的经验 kafka架构概念 explain分析sql语句字段的解释 JVM问题分析处理手册 logstash过滤器(2)date logstash过滤器(3)dissect logstash编码器(1)json logstash编码器(2)multiline logstash表达式 logstash输入(1)通用选项 logstash输入(3)file logstash过滤器(1)通用选项 logstash输入(2)stdin logstash安装 记一次前端vConsole导致JSON序列化错误排查 解决多个异步操作嵌套问题 fastjson反序列化失败autoType is not support RTMP串流服务 POI自动调整列宽错误 Nginx+Lua实现动态黑名单 使用curl命令模拟POST和GET请求 ResponseEntity下载文件
Groovy加载类导致OOM分析
祈雨的笔记 · 2021-11-20 · via 祈雨的笔记

现象

项目中需要使用动态规则引擎,因此对热门的Groovy进行了调研。但早先就对Groovy会有OOM的问题有所耳闻,因此调研的时候特地关注了高频率使用Groovy加载类的场景,结果果然与预期一直稳定复现OOM故障。

分析

复现场景

1
2
3
4
5
6
7
8
9
10
11
12
13
GroovyClassLoader loader = new GroovyClassLoader();
for (int i = 0; ; i++) {
String source = "" +
"public class CustomApplication {\n" +
" public void print() {\n" +
" System.out.println(\"" + i + "\");\n" +
" }\n" +
"}";
Class<?> clazz = loader.parseClass(source);
Object target = clazz.newInstance();
Method method = clazz.getMethod("print");
method.invoke(target);
}

执行以上代码,并通过JVM自带的jconsole工具监控类加载数量和元数据区的内存,如下图所示。监控显示,JVM的类数量从三千一路飙升到一万三,元数据内存使用也是一路飙涨,直到OOM后应用报错。

image

image

分析OOM

通过以上两张图,显而易见,应用OOM的原因是Groovy加载的类即使只使用一次,但却并没有被释放,最终导致元数据内存空间不足而OOM。因此接下来的思路是需要分析类如何才能被回收释放,以及如何才能让Groovy加载的类回收释放掉。

首先分析一个类的回收的前置条件,一个类如果需要被垃圾回收,则需要同时满足下面3个条件:

  1. 该类所有的实例都已经被回收
  2. 加载该类的ClassLoader已经被回收
  3. 该类对应的java.lang.Class对象没有在任何地方被引用,无法在任何地方通过反射访问该类的方法

对照复现场景中的测试代码,显然条件1和条件3是满足的,所有的类对象和类实例都没有被外部持有。至于条件2则需要了解Groovy的类加载机制才能解答。

Groovy类加载机制

Groovy加载类的核心逻辑在groovy.lang.GroovyClassLoader#doParseClass,其实现细节是通过GroovyClassLoader对象执行parseClass方法尝试加载类时,实际是每次类加载都会新建一个新的GroovyClassLoader.InnerLoader类加载器来真正执行类加载,加载完成后则不再引用该GroovyClassLoader.InnerLoader类加载器对象。

1
2
3
4
5
6
7

ClassCollector collector = createCollector(unit, su);
unit.setClassgenCallback(collector);
int goalPhase = Phases.CLASS_GENERATION;
if (config != null && config.getTargetDirectory() != null) goalPhase = Phases.OUTPUT;

unit.compile(goalPhase);
1
2
3
4
5
6
7
8
protected ClassCollector createCollector(CompilationUnit unit, SourceUnit su) {
InnerLoader loader = AccessController.doPrivileged(new PrivilegedAction<InnerLoader>() {
public InnerLoader run() {
return new InnerLoader(GroovyClassLoader.this);
}
});
return new ClassCollector(loader, unit, su);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static class ClassCollector extends CompilationUnit.ClassgenCallback {
private Class generatedClass;
private final GroovyClassLoader cl;
private final SourceUnit su;
private final CompilationUnit unit;
private final Collection<Class> loadedClasses;

protected ClassCollector(InnerLoader cl, CompilationUnit unit, SourceUnit su) {
this.cl = cl;
this.unit = unit;
this.loadedClasses = new ArrayList<Class>();
this.su = su;
}

public GroovyClassLoader getDefiningClassLoader() {
return cl;
}

protected Class createClass(byte[] code, ClassNode classNode) {
BytecodeProcessor bytecodePostprocessor = unit.getConfiguration().getBytecodePostprocessor();
byte[] fcode = code;
if (bytecodePostprocessor!=null) {
fcode = bytecodePostprocessor.processBytecode(classNode.getName(), fcode);
}

GroovyClassLoader cl = getDefiningClassLoader();
Class theClass = cl.defineClass(classNode.getName(), fcode, 0, fcode.length, unit.getAST().getCodeSource());
this.loadedClasses.add(theClass);

if (generatedClass == null) {
ModuleNode mn = classNode.getModule();
SourceUnit msu = null;
if (mn != null) msu = mn.getContext();
ClassNode main = null;
if (mn != null) main = (ClassNode) mn.getClasses().get(0);
if (msu == su && main == classNode) generatedClass = theClass;
}

return theClass;
}

...
}

通过arthas工具监控类加载器如下图,通过GroovyClassLoader对象加载类时,实际上是使用的GroovyClassLoader.InnerLoader对象加载目标类,且每个GroovyClassLoader.InnerLoader类加载器对象只加载一个类。

image

漏网之鱼

我们再回忆一下一个类的回收的3个前置条件:

  1. 该类所有的实例都已经被回收
  2. 加载该类的ClassLoader已经被回收
  3. 该类对应的java.lang.Class对象没有在任何地方被引用,无法在任何地方通过反射访问该类的方法

测试代码中条件1和条件3满足,根据Groovy的类加载机制,明显类加载器加载完成目标类后就不再引用,因此条件2也满足,但实际上类并没有按预期被垃圾回收。显然在测试代码之外,有代码引用到了类对象或者类实例亦或者类加载器,导致最终类木有被垃圾回收。

这里就需要借助其他工具来分析对象引用,为了方便分析,使用OOM的内存快照,来分析导致内存溢出的对象,可直接定位到被偷偷引用的漏网之鱼。

image

image

如上图,最终定位出java.beans.ThreadGroupContext下引用了类对象,因此上述的类回收的3个条件未满足而导致类不会被垃圾回收。

那么问题来了,类对象为什么会被java.beans.ThreadGroupContext引用?经过层层debug后发现,当对Groovy加载的类执行反射时,会将该类的结构缓存到java.beans.ThreadGroupContext中,且不会主动清除缓存。核心代码如下:

groovy.lang.MetaClassImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

private void addProperties() {
BeanInfo info;
final Class stopClass;

try {
if (isBeanDerivative(theClass)) {
info = (BeanInfo) AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IntrospectionException {

return Introspector.getBeanInfo(theClass, Introspector.IGNORE_ALL_BEANINFO);
}
});
} else {
info = (BeanInfo) AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IntrospectionException {

return Introspector.getBeanInfo(theClass);
}
});
}
} catch (PrivilegedActionException pae) {
throw new GroovyRuntimeException("exception during bean introspection", pae.getException());
}
...
}

java.beans.Introspector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static BeanInfo getBeanInfo(Class<?> beanClass)
throws IntrospectionException
{
if (!ReflectUtil.isPackageAccessible(beanClass)) {
return (new Introspector(beanClass, null, USE_ALL_BEANINFO)).getBeanInfo();
}

ThreadGroupContext context = ThreadGroupContext.getContext();
BeanInfo beanInfo;
synchronized (declaredMethodCache) {
beanInfo = context.getBeanInfo(beanClass);
}
if (beanInfo == null) {
beanInfo = new Introspector(beanClass, null, USE_ALL_BEANINFO).getBeanInfo();
synchronized (declaredMethodCache) {
context.putBeanInfo(beanClass, beanInfo);
}
}
return beanInfo;
}

解决

综上,虽然Groovy通过GroovyClassLoader.InnerLoader来加载类,实现类加载器在类加载完成后就会被垃圾回收,但由于Groovy加载的类在反射时会被java.beans.ThreadGroupContext缓存,且该缓存不会被主动清除,因此最终类没有按预期被垃圾回收。

所以只要定期清除java.beans.ThreadGroupContext中的缓存,就能释放所有类引用,让Groovy加载的类被垃圾回收。测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
GroovyClassLoader loader = new GroovyClassLoader();
for (int i = 0; ; i++) {
String source = "" +
"public class CustomApplication {\n" +
" public void print() {\n" +
" System.out.println(\"" + i + "\");\n" +
" }\n" +
"}";
Class<?> clazz = loader.parseClass(source);
Object target = clazz.newInstance();
Method method = clazz.getMethod("print");
method.invoke(target);

if (i % 100 == 0) {

Introspector.flushCaches();
}
}

如下图,图1为类加载数量图,其中红线为累计加载类数量,蓝色为当前加载类数量,而图二为元数据内存使用情况。可见在定期清除ThreadGroupContext中的缓存后,实现了对Groovy加载类的垃圾回收,不再出现OOM的问题。

image

image