Reliability of protected void finalize() for freeing native dynamic memory
In different places, I've been reading different things about the specification of garbage collection in Java. From what I've found so far, it is pretty clear thatif the garbage collector of the VM used decides to reclaim object X, then X.finalize() is called. However, opinions vary on whether the garbage collector will ever decide to reclaim X.
I'm using the JNI and, unfortunately, have to keep a few bits in memory on the native side. Even worse, I keep those bits in dynamic memory (allocated with C's malloc). These chunks of memory always correspond to a single object on the Java side, so I thought it would be a good idea to have my objects in the native interface include this bit of code:
nativevoid free();
protectedvoid finalize()throws Throwable{
Exception x =null;
try{
free();
/* whatever other destruction seems usefull */
}catch(Exception e){
CentralHandler.handle(this, e);
x = e;
}finally{
try{
super.finalize();
}catch(Exception e){
CentralHandler.handle(this, e);
if(x !=null)
throw CentralHandler.combine(x,e);
}
}
}
I have been told the problem with this is that I can't be sure the garbage collector will ever clear out this object, even when the program comes to an end (inside the VM; when the VM itself is killed, the user's on his own). Does it matter if finalize is never called and will all my malloc-ed memory just become free with the disappearance of the VM?

