Lazy loaded image
使用阿里云SDK通过InputStream上传文件导致的堆内存溢出
Words 530Read Time 2 min
2025-3-12
2025-3-13
type
status
date
slug
summary
tags
category
icon
password

1.项目场景

OSS中有原图(原图会周期冻结-所以需要生成对应缩略图使用), 采用OSS image/resize,w_1920/quality,q_75添加参数的方式获取图片缩略图, 然后将缩略图进行重新上传

2.原代码

内存和cpu逐渐达到峰值, 此时进程已经卡死
notion image
notion image

3.修改后

使用try-with-resources手动释放
notion image
notion image
 

4.使用定时任务进行手动GC

notion image
notion image
notion image
💡
仔细观察到Heap Dump中有java.security.cert.TrustAnchor的对象占用很大,
GC无法进行内存的释放,内存对象处于一直引用的抓过你太,猜测可能是OSSClient未释放,连接一直有效
notion image
创建OSSClient的代码如下

5.解决方案

将创建OSSClient修改为单例创建,问题解决
notion image
 
💡
在项目实践中,尽可能的自己手动回收InputStream,防止内存溢出
针对一些工具的创建,尽可能采用单例模式,防止无用的内存消耗
 
上一篇
BigDecimal.equals()问题
下一篇
Win家庭版开启远程桌面