is there an elegant way in Java to set all existing object-pointers to null? I开发者_如何学C want an object to be deleted, but it is registered in several places an Event Listener.
You can take a look at References. If you use a reference to refer to the class, it will not prevent an object from being garbage collected when all of the regular references are removed. The references held by the Reference
class doesn't count when the collector determines which objects to collect. Of course, the listeners will have to correctly handle the reference suddenly disappearing. And you'll have to make sure something's keeping a regular reference for as long as you need to class to stick around.
Check out this thread for a discussion about the differences between the soft and weak references. What is the difference between a soft reference and a weak reference in Java?
There is no elegant way for that. Don't try to do it or you will end up with difficult to maintain code.
Not explicitly, no. And there's a good reason for that - it's just not the way garbage collection works in Java!
If you really want to do this (though I'm saying this mostly for academic purposes, I'd strongly advise not doing it) the best approach I can think of is potentially wrapping up all references to the object in WeakReferences, and pass those around, just holding onto one strong reference to your object. If you set that strong reference to null then all the weak references to that object become eligible for garbage collection.
Of course, you need to be aware that as soon as the hard reference is set to null, the WeakReferences could disappear randomly at any time afterwards. So you need to make sure all your code using them is ready to handle that.
That said, that route is almost not the best to go down, and will make your code a lot harder to maintain! Ensuring that they're all released as they go out of scope nicely would be by far the better alternative, and shouldn't be hard if the rest of your code is neat enough.
A few notes:
You can not control object deletion in Java. This a job of garbage collector. You can instruct GC to do garbage collect, but this does not guarante object will be in fact deleted.
In practical terms object is deleted when it can not be reached anymore. If you delete all references to it then you can not reach it anymore.
With Java, you can't do that with references. You could create a deterministic Dispose
method that empties the values in a reference like .NET's IDisposable
.
精彩评论