Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File deleteOnExit() function keeps Reference Pointer open even after the file is deleted

Tags:

java

file

linux

io

  1. I am creating temporary files in my application using java.io.File.createTempFile().
  2. While creating file, I have called deleteOnExit() for that File object.

This code is used in many scenarios in my application. Sometimes, the size of temp files is too large and so I have to delete it immediately after my job is completed. So I am calling File.delete() for some objects.

Now the problem is, when I delete the file using delete() function, the reference pointer is open for this deleted file(because of it being temp file(My opinion)). Because of this, I am facing memory leakage issue.

(Correct me if I am wrong on my above hypothesis)

I am facing high disk utilization on my environment, I found a discrepancy of over 30GB in the output of the 'df' and 'du' command ('df' looks at the stat of the FS itself whereas 'du' ignores deleted file descriptors).

  1. If I remove deleteOnExit(), I will have to take care of deleting all the objects manually. Doing this, my pointers are still remaining open(Used lsof +al1 on linux to see open files) Why is this happening?
  2. If I remove delete(), then I will have to wait until VM stops to get tempFiles deleted(which is a very rare case in Production Server). (Huge Space Utilization)

Is there any Solution on how I can remove file from deleteOnExit() list if I am manually deleting the file?

like image 640
SID Avatar asked May 12 '26 17:05

SID


2 Answers

I suspect that your analysis is correct, and that could be seen as a bug in Java: once you call delete, it would be fair to expect the reference created by deleteOnExit to be be removed.

However, we are at least warned (sort of). The Javadoc for deleteOnExit says:

Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.

So I guess calling delete after deleteOnExit would be considered careless.

However, it seems to me that your question implies its own solution. You say:

If I remove delete(), then I will have to wait until VM stops to get tempFiles deleted(which is a very rare case in Production Server).

If the JVM is very rarely ended, then deleteOnExit will very rarely do you any good. Which suggests that the solution is to handle your own deletions, by having your application call delete when it is finished with a file, and note use deleteOnExit at all.

like image 195
Martin McCallion Avatar answered May 14 '26 07:05

Martin McCallion


The pointer will remain open until the application releases the resource for that file. Try

fileVar = null;

after your

fileVar.delete();
like image 31
anitag95 Avatar answered May 14 '26 09:05

anitag95