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

查看:149
本文介绍了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天全站免登陆