views:

87

answers:

3

HI,

There is a strange out of memory error issue.

I create a class to parse live streaming, and the class needs buffers to keep these raw data.

Here are code snippets:

/* Initial and uninitial buffer in class */
private final int MAX_BUFFER = 16;
protected byte[][] m_byStreamBuf = null; // Frame buffer
public void InitBuffer() {
  m_byStreamBuf = new byte[MAX_BUFFER][];
  m_byStreamBuf[0] = new byte[512*1024]; // for I Frame
  for (int i = 1; i < MAX_BUFFER; i++) {
    m_byStreamBuf[i] = new byte[256*1024]; // for P frame   
  } 
}

public void UninitBuffer {
  this.m_byStreamBuf = null;
  System.gc();
}

Out of memory error will occur after start and close the application several times(maybe three or four times actually).

I check that the error occurs on the line which allocates memory.

I have try to call System.gc() when close application every time.

But it seems that the application still allocate too much memory and do not release all of them.

Thanks for any suggestion.

Regards,

Caxton

A: 

I have try to call System.gc() when close application every time.

That definitely won't help. Java will automatically run the garbage collector if it is running short of space. You only get an OOME if the GC has failed to free up enough memory. (Actually, that's an over-simplification ... but that's beyond the scope of your question.)

If you are running out of memory, it will be because something is preventing your application instances from going away after they have finished. Maybe there's something an application is supposed to do when it is finished that yours is not doing.

One hacky fix would be to assign null to m_byStreamBuf when your application finishes. But that still leaves lesser memory leaks.

Stephen C
A: 

Create weak references

Suresh S
I don't think soft/weak refs would work in this case since it's somehow holding a strong reference elsewhere. Plus, it's not an optional cache that can be recovered since it's flowing in from a live stream.
j flemm
A: 

This class alone should not be causing out of memory error as it is barely using the heap (15*256*1024+512*1024=4456448=~5MB??). However, multiple instances will. Somewhere in your application, perhaps you are creating a lot of instances of this class and not releasing them properly.

Since you also mentioned that this happens after several restarts of the application, then memory leak is also possible. You may also look at classloader leaks here http://blogs.sun.com/fkieviet/entry/classloader_leaks_the_dreaded_java

These things are not easy to investigate but there are the usual suspects. Good luck! :)

Adrian M