Reputation: 3913
I have some library code that uses File.deleteOnExit()
. As this piece of code is called a lot in my application, memory keeps piling up in DeleteOnExitHook
. This causes my heap to grow indefinitely and eventually causes OutOfMemoryErrors
. As the class is completely package protected, there seems trivial mechanism to intermediately delete the files enqueued for deletion. Can I get this empty this list with some reflection magic?
Upvotes: 0
Views: 352
Reputation:
As I understand, you need a dirty hack, so this should suffice. You need to restore files
field value so that normal shutdown (or next time you use this hack) works fine.
Note: will delete everything, including files scheduled by other libraries. Make sure to check it is safe in your case.
java.lang.reflect.Method run = Class.forName ("java.io.DeleteOnExitHook").getDeclaredMethod ("runHooks");
java.lang.reflect.Field files = Class.forName ("java.io.DeleteOnExitHook").getDeclaredField ("files");
run.setAccessible (true);
files.setAccessible (true);
run.invoke (null);
files.set (null, new java.util.LinkedHashSet <String> ());
Alternatively, just retrieve the scheduled files with
files.get (null)
iterate the set and delete the files manually, also deleting the names from the set as you go. This way you can decide which files to delete yourself.
Upvotes: 1