Java写入ByteArrayOutputStream内存泄漏 [英] Java writing to ByteArrayOutputStream memory leak

查看:142
本文介绍了Java写入ByteArrayOutputStream内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将图像字节写入ByteArrayOutputStream,然后通过套接字发送. 问题是,当我这样做

I am writing bytes of image to ByteArrayOutputStream then sending it over socket. The problem is, when I do

ImageIO.write(image, "gif", byteArray);

内存增加很多,有点内存泄漏.

Memory goes up VERY much, kinda memory leak.

我使用此

ImageIO.write(image, "gif", byteArrayO);         
byte [] byteArray = byteArrayO.toByteArray();
byteArrayO.flush();
byteArrayO.reset();
Connection.pw.println("" + byteArray.length);
int old = Connection.client.getSendBufferSize();
Connection.client.setSendBufferSize(byteArray.length);
Connection.client.getOutputStream().write(byteArray, 0, byteArray.length);
Connection.client.getOutputStream().flush();
image.flush();
image = null;
byteArrayO = null;
byteArray = null;
System.gc();
Connection.client.setSendBufferSize(old);

如您所见,我已经尝试了所有方法,该错误在我写入ByteArrayOutputStream时发生,而不是在传输它时出现.接收方没有任何错误.

As you can see I have tried all ways, the error comes when I write to the ByteArrayOutputStream, not when I transfer it. The receiver does not get any errors.

有什么办法可以清除byteArray,并从内存中删除其中的所有内容?我知道reset()可以,但是这里没有.完成后,我想直接处置ByteArrayOutputStream.

Any way I can clear the byteArray, and remove everything it has in it from memory? I know reset() does, but it dont in here. I want to dispose of the ByteArrayOutputStream directly when this is done.

推荐答案

@ChristofferHammarström可能是最好的解决方案,但是我将添加它来解释内存使用情况.

@Christoffer Hammarström probably has the best solution, but I'll add this to try to explain the memory usage.

这两行正在创建您的图像数据的3个副本:

These 2 lines are creating 3 copies of your image data:

ImageIO.write(image, "gif", byteArrayO);
byte [] byteArray = byteArrayO.toByteArray(); 

执行此操作后,将有一个数据副本存储在图像中,一个副本在ByteArrayOutputStream中,另一个副本在字节数组中(toByteArray()不返回它创建副本的内部缓冲区).

After executing this you have one copy of the data stored in image, one copy in the ByteArrayOutputStream and another copy in the byte array (toByteArray() does not return the internal buffer it creates a copy).

调用reset()不会释放ByteArrayOutputStream内部的内存,它只是将位置计数器重置为0.数据仍然存在.

Calling reset() does not release the memory inside the ByteArrayOutputStream, it just resets the position counter back to 0. The data is still there.

要允许更早地释放内存,您可以在完成后将每个项目分配为null.如果它决定较早运行,这将允许垃圾收集器收集内存. EG:

To allow the memory to be released earlier you could assign each item to null as soon as you have finished with it. This will allow the memory to be collected by the garbage collector if it decides to run earlier. EG:

ImageIO.write(image, "gif", byteArrayO);
image = null;
byte [] byteArray = byteArrayO.toByteArray(); 
byteArrayO = null;
...

这篇关于Java写入ByteArrayOutputStream内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆