简体   繁体   English

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;
}

As I have read here: BufferedImage.getGraphics() resulting in memory leak, is there a fix? 正如我在这里阅读的: BufferedImage.getGraphics()导致内存泄漏,是否有修复程序? .createGraphics() is the problem. .createGraphics()是问题所在。

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). 该代码可以经常执行(将计时器设置为以50ms的恒定速率计时,如果灯光“移动”,它将调用此代码,但是如果灯光停留在同一位置,则将其跳过)。 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. 它运行良好,但每次都会使进程变得笨拙,这是一个级联进程,最终导致在不到一分钟的时间内从约18万个内存增加到超过60万个内存。 Graphically it works fine until at some point the clunk becomes too much (obviously) and FPS drop drastically. 从图形上讲,它可以正常工作,直到在某些时候结块变得过多(显然)并且FPS急剧下降为止。

Now I have narrowed down that this block produces the leak as commenting its call out makes the problem go away. 现在,我缩小了范围,认为此块会产生泄漏,因为注释它的调用使问题消失了。

The base image drawn is 1024x561 and the lights' images are rather small (50x50). 绘制的基本图像为1024x561,灯光的图像很小(50x50)。 I have always been testing it with only one light in the array so far. 到目前为止,我一直只用阵列中的一盏灯对其进行测试。

Any solutions to avoiding the memory leak? 有什么解决方案可以避免内存泄漏?

As Andrew Thompson commented, this is not necessarily a memory leak. 正如安德鲁·汤普森(Andrew Thompson)所说,这不一定是内存泄漏。 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 您可以尝试在灯光不动的情况下尝试System.gc()调用,尽管通常不建议调用System.gc(): 什么时候System.gc()做任何事情

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后面的整数数组(不容易),或者使用其他API(如JOGL)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM