Can a Java object tell when a reference to it goes out of scope?
05:27 15 Feb 2016

I'm fantasizing of a tool to detect resource leaks. I have a good idea what the tool should look like and what the requirements are, but I lack one piece of the puzzle to make it work: an event occurring when a reference goes out of scope.

The tool would work like this: When a closeable is created, the tool builds a wrapper around it. When close() is called, the wrapper marks the object closed. When the object becomes garbage-collectable, if the object has not been closed, it delivers a stack trace of the current thread, identifying where in the code we are abandoning the object without closing it.

Sounds nifty, but I have not found any events that occur when references go out of scope. There are finalization and phantom reference events, but these occur in a different thread, after the guilty party has already vacated the scene of the crime. I need something like a method I can override that is called on reference release.

Any ideas for me?

TIA, - Tim.

java reference resource-leak