Skip to content

Can Javascript objects have an “on garbage collect” callback?

I’m writing an Android app which uses Javascript in a WebView for most of the UI. I’ve exposed to JS a simple interface to create temporary files. In Java, I provide a function to create a temporary file, which returns a file ID, and a set of functions to operate on temporary files given an ID. In JS, I wrap these functions with a TempFile object which keeps track of its own ID internally.

The problem with this is the Java side has a list of files, but knows nothing about the objects that represent them in Javascript. So when a TempFile is collected in JS, the file object is still around on the Java side. Is there an “oncollect” or such callback that I can use to tell Java to free the file corresponding to a TempFile that’s been collected?


I’m fairly sure the answer is “no” – you can’t hook into the JS garbage collection process in the same way that you can with Java’s finalizers (or ReferenceQueues).

Can you instead deal with this more declaratively? Your question seems to imply that the only way your system “knows” when a file is no longer needed, is when it is GCed (or in other words, your system doesn’t know at all). Are you really referencing these files all over the application? Good practice would be for these resources to be used with a well-defined lifecycle, such that the part of the system that creates a temp file is also responsible for destroying it after it’s finished with it.

Under that model, when you (explicitly) destroy the file in JS, you can call back to Java to perform the required clean up.

Releasing a resource by simply removing all references to it, as you’re doing at the moment, is not particularly good practice.