BufferedImage.createGraphics()内存泄漏 [英] BufferedImage.createGraphics() memory leak
问题描述
下面的代码会导致内存泄漏.
The code below produces a memory leak.
public static BufferedImage mergeImages2(BufferedImage base, Collection<Light> images) {
BufferedImage output = new BufferedImage(base.getWidth(), base.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = output.createGraphics();
g.drawImage(base, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 1.0f));
for (Light l : images) {
g.drawImage(l.LIGHT_IMAGE, l.x, l.y, null);
l.LIGHT_IMAGE.flush();
}
g.dispose();
output.flush();
return output;
}
正如我在这里阅读的内容: BufferedImage.getGraphics ()导致内存泄漏,是否可以解决? .createGraphics()是问题所在.
As I have read here: BufferedImage.getGraphics() resulting in memory leak, is there a fix? .createGraphics() is the problem.
此代码可以经常执行(将计时器设置为以50ms的恒定速率计时,如果灯光移动",它将调用此代码,但是如果灯光停留在相同的位置,则将被跳过).它运行良好,但是每次都会使进程变得笨拙,这是一个级联进程,最终导致在不到一分钟的时间内从约18万个内存增加到超过60万个内存.从图形上讲,它可以正常工作,直到某个时候结块变得过多(显然)并且FPS急剧下降为止.
This code can be executed quite often (a timer is set up to tick at a constant rate of 50ms and if a light is "moving" it calls this code, but if lights stay in the same place this is skipped). It runs fine but everytime makes the process clunk memory, which is a cascade process eventually leading to an increase from ~180 000 K memory to more than 600 000 K memory in less then one minute. Graphically it works fine until at some point the clunk becomes too much (obviously) and FPS drop drastically.
现在我已经缩小了范围,认为此块会导致泄漏,因为注释它的调用使问题消失了.
Now I have narrowed down that this block produces the leak as commenting its call out makes the problem go away.
绘制的基本图像为1024x561,灯光的图像很小(50x50).到目前为止,我一直只用阵列中的一盏灯对其进行测试.
The base image drawn is 1024x561 and the lights' images are rather small (50x50). I have always been testing it with only one light in the array so far.
是否有避免内存泄漏的解决方案?
Any solutions to avoiding the memory leak?
推荐答案
正如安德鲁·汤普森(Andrew Thompson)所说,这不一定是内存泄漏.垃圾收集器的启动可能比您想象的要晚.您可以尝试在灯光不动时尝试System.gc()调用,尽管通常不建议调用System.gc():
As Andrew Thompson commented, this is not necessarily a memory leak. The garbage collector might simply start later than you think. You could try experimenting with a System.gc() call, when the lights are not moving, although generally calling System.gc() is not recommended: When does System.gc() do anything
或者,您可以尝试直接操作BufferedImage后面的整数数组(不容易),或者尝试使用其他API(例如JOGL).
Alternatively you could try to manipulate directly the integer arrays that are behind your BufferedImage (not easy), or perhaps to use another API (like JOGL).
这篇关于BufferedImage.createGraphics()内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!