Java ByteArrayOutputStream在内存中泄漏 [英] Java ByteArrayOutputStream leaks in memory

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

问题描述

我提出了一个新问题,因为这与我的上一个主题有所不同.我现在知道更确切的问题了.

I made a new question because this is different from my last thread. I now know what th e problem is more exact.

我创建了一个新的bytearrayoutputstream

I create a new bytearrayoutputstream

ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

没什么特别的. 然后,当我向其中写入图像时,这种方式

Nothing special. Then, when I write an image to it, this way

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

首先,内存增加了大约100 mb,而不是在月食中,而是在现实"中.然后,每次我向该流或另一个流中写入新图像后,它就会缓慢增加!

the memory increases like 100 mb first, not in eclipse, but in "reality". Then it slowly increases after that each time I write a new image to that stream OR another!!

一段时间后它停止工作并有点崩溃.

and after a while it stops working and kinda crashes.

我已经尝试关闭它以及所有这些东西,刷新,重置所有内容,但是它仍然会泄漏内存.当我停止使用byteArray或将其为null时,我希望它脱离内存.

I have tried closing it and all that, flushing, reseting, everything, but it still leaks memory. I want it to get away from memory when I stop using byteArray or null it.

System.gc();

在这种情况下不会提供帮助.

wont help in this case.

请帮助我,您需要知道的其他事项我会回答,请返回并回复:)

Please help me and anything else you need to know I will answer and please return and reply back :)

推荐答案

请参考我发布到另一个ByteArrayOutputStream问题的类似答案.

ByteArrayOutputStream中没有允许您缩小缓冲区的方法.重置会更改缓冲区中的位置.

There is no method in ByteArrayOutputStream that allows you to shrink the buffer. Reset changes the position in the buffer.

您的解决方案是

  1. 使用构造函数在使用前指定缓冲区的大小.将大型对象写入流时,这将节省大量内存并防止OOM异常.
  2. 如果要重用BAOS对象,请调用reset.这将使下一次写操作从缓冲区的开头开始.
  3. 释放内存的唯一方法是删除所有对其的引用.在上面的代码中,您会说byteArray = null;

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

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