Skip to content Skip to sidebar Skip to footer

How To Handle Memory Leaks While Continuous Insertion In A Linkedlist?

I have following function which is called continuously from run() of a Thread which is continuously running. private LinkedList playerData = new LinkedList

Solution 1:

Your problem won't be solved by explicitly deleting objects ... basically because there is no way to do that in Java.

If you are really creating too much garbage for the CMS collector to cope with, then the only solution is to use an object pool to recycle the buffer objects instead of dropping them on the floor for the GC to deal with. However, you need to be careful that you don't replace your current problem with others:

  • The recycled objects may need to be "cleaned" (zeroed).
  • A poorly designed object pool can be a memory leak.
  • A poorly designed object pool can be a concurrency bottleneck.
  • A poorly designed object pool can increase GC overheads, especially if you are running with a heap that is too small.

On the other hand, your real problem may be that your heap is too small for the application you are trying to run. If you run too close to the limit, the GC won't reclaim much garbage each time. Since the cost of running the GC is proportional to the amount of NON-garbage, it is easy to see that the GC's efficiency is non-linear as the heap gets closer to full.

Solution 2:

Simply set your objects to NULL after use and the Garbage Collector will automatically take care of it. Practically Garbage Collector kicks in when your objects are not accessible by the code, so it destroys them to free up space.

Solution 3:

Java does not have delete operator. The garbage collector destroys the object automatically when the code parts do not use them anymore.

That is when an object becames unreachable, the garbage collector destroy that object and free the memory related.

I read the edit, maybe you can solve your problem with a byte[] buffers pool. So the garbage collector does not need to garbage all the time the buffers.

private LinkedList playerData = new LinkedList();

publicsynchronizedvoidsetPlayerData(short[] buffer) {
  // Log.i(LOG_TAG, "Inside setData..");
  playerData.addLast(buffer);
  if (playerData.size() > 10) {
    // Log.i(LOG_TAG, "playerData not empty");
    byte[] buffer = playerData.removeFirst();
    // here return the buffer to the pool to reuse it
  }

  }

Solution 4:

If you are having problems with the garbage collector the best thing is to allocate less new memory. One way of doing this is to use object pools. Basically, reuse a buffer you no longer need instead of creating a new one.

Solution 5:

There is no "equivalent" operator in Java. The system performs garbage collection in the background. No explicit method call will guarantee that memory will be freed immediately.

Post a Comment for "How To Handle Memory Leaks While Continuous Insertion In A Linkedlist?"