Tuesday, April 02, 2013

Releasing resource in Java (no destructor)

I needed to release resource in Java class and thinking about C++ style of resource management in class (open in constructor and release it in destructor). It turns out that there is no destructor in Java (finally doesn't cut it). So instead of open the resource in constructor and release it in destructor I should open it locally in the function and use try finally construct. Something like below (quoted from StackOverflow link on references list below) :

Resource r = new Resource();
try {
    //work
} finally {
    r.dispose();
}

Not as elegant as having the real destuctor (I'll need to use the above locally in every functions that needed it) but it gets the job done.

References :

http://stackoverflow.com/questions/171952/is-there-a-destructor-for-java
http://c2.com/cgi/wiki?FinalizeInsteadOfProperDestructor