NIO & Buffers - Memory leaks ?

Garbage Collector seem to have some difficulties to free (delete from the memory) NIO Buffers objects ie ByteBuffer, IntBuffer ...
Unused buffers continue to reside in the memory long time after they are finished to be used.

IMPORTANT NOTICE: This article may be wrong with current version of java. Effectively, garbage collection seem to have been improved and for what I've seem NIO buffers are now garbaged earlier.
 

Consequences are a higher use of memory, memory goes higher and higher (at each loop) ...
This can slow down your application and may be the system is memory goes to high.
 

To solve this, just a call to java.lang.System.gc().
I've made some tests with java.lang.System.gc(), all buffers are well removed. Without the call, I've remark that memory own by buffers are not deallocated.

FMOD Ex loop should looks like this :

FMOD Ex loop (1)

do {
    //Do what should be done here
    ...
   
    //Update FMOD Ex system
    system.update();
   
    //Call Garbage Collector to free some memory
    java.lang.System.gc();
   
    try {
        Thread.sleep(10);
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
} while(...);

Calling Garbage Collector like this is CPU expensive. An alternative to this is to put it in another Thread and call it less time.
I recommend you this way (you can increase UPDATE_TIME value) :

FMOD Ex loop (2)

Thread cleanup = new Thread() {
    private final static int UPDATE_TIME = 2000;
    public void run() {
        while(...) {
            //Call Garbage Collector to free some memory
            java.lang.System.gc();

            try {
                Thread.sleep(UPDATE_TIME);
            } catch(InterruptedException e){}
        }
    }
};
cleanup.start();

do {
    //Do what should be done here
    ...
   
    //Update FMOD Ex system
    system.update();
   
    try {
        Thread.sleep(10);
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
} while(...);

 

Last modified on 04/10/2010
Copyright © 2004-2010 Jérôme JOUVIE - All rights reserved. http://jerome.jouvie.free.fr/