I have an ImageWrapper class that saves images to temporary files on disk to free up heap memory and allows them to be reloaded if necessary.
class ImageWrapper { File tempFile; public ImageWrapper(BufferedImage img) { // save image to tempFile and gc() } public BufferedImage getImage() { // read the image from tempFile and return it. } public void delete() { // delete image from disk. } }
I am worried about making sure that the files are deleted when such an instance of ImageWrapper collects garbage (otherwise I risk filling the disk with unnecessary images). This needs to be done while the application is still running (unlike cleaning suggestions at the time of completion) due to the fact that it can run for a long time.
I'm not completely familiar with the Java Java concept, and I was wondering if finalize() is what I'm looking for. My idea was to call delete () (in a separate thread, if that matters) from the overriden finalize() method. Is this the right way to do this?
UPDATE:
I do not think that I can close() an object proposed by many users, because each such image is selected in the list of listeners that I do not control, and could save a link to the object. the only time I'm sure I can delete a file when there are no links, so I thought finalize() was the right way. Any suggestions?
UPDATE 2:
What are the scenarios in which finalize() will not be called? If the only way to exit the program is (expected / unexpected), I can accept this because it means that I risk that only one unnecessary temporary file will remain un deleted (the one that was processed during the exit).
source share