Java BufferedArrayOutputStream leaks in memory

那年仲夏 提交于 2019-12-11 05:59:09

问题


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

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

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.

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 :)


回答1:


Your usage pattern should be like:

while( keepRunning) {
     ByteArrayOutputStream byteArray = new ByteArrayOutputStream();   
     ImageIO.write(image, "gif", byteArray);
}

If you do this faster than the JVM can collect garbage you'll eventually get a very long GC pause or an OutOfMemory exception.




回答2:


Have you tried this:

 try{
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ImageIO.write(image, "png", baos);
  baos.flush();
  byte[] imageBytes = baos.toByteArray();
  baos.close();
}catch(Exception ex){
  System.out.println(ex.getMessage());
}



回答3:


What you are doing doesn't make any sense. You're taking an image out of memory and put it into memory again, this time as byte array.

You should put that image into a file or send over the network. Or, if you want just hold a copy, copy the image (not the byte array!) like I described here: Bug in using Object.clone()




回答4:


Please refer to a similar answer I posted to another ByteArrayOutputStream question.

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

The solution for you is to

  1. Use the constructor to specify the size of the buffer before use. When you are writing large objects to the stream, this will save a lot of memory and prevent OOM exceptions.
  2. If you want to reuse your BAOS object, call reset. That will make the next write start at the beginning of the buffer.
  3. The only way to free the memory is to remove all references to it. In the code above, you would say byteArray=null;


来源:https://stackoverflow.com/questions/11957981/java-bufferedarrayoutputstream-leaks-in-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!