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 {
} finally {

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 :


No comments: