简体   繁体   中英

Can a Java object tell when a reference to it goes out of scope?

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.

Strictly speaking, a reference doesn't go out of scope. Variables go out of scope. References are values ... and don't have scopes.

There is no mechanism in Java that allows an object (or manager) to be informed when any reference variable containing its reference goes out of scope. The closest that is a try-with-resources that will automatically call close() on a declared resource variable when the try block terminates. (But that most likely won't help you detect the cases you are trying to detect.)

There is no mechanism in Java that allows an object (or manager) to be informed when it becomes unreachable. There are mechanisms such as finalize() , PhantomReference , and Cleaner (new in Java 9) that can be used to detect that an object has become unreachable some time earlier. But these mechanisms rely on the GC, and detection typically happens a long time after the "event" of becoming unreachable, and they don't tell you which reference variables were involved.


Other languages where storage management is less automatic do provide ways to do this. But there is a downside too. For example, C++ smart pointers will not detect the cases involving object cycles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM