I have a Java class which needs a monitor running parallel when instantiated. I want to keep running this monitor until the instance is not running any more or it is not referenced. Usually I tend to use a active flag as a variable, which is closed when the class is shutdown/closed, however this has to be managed carefully and it has to be called when closing. I am also aware of the finalize member of Object but as I remember it is not safe to use it or is it for this purpose? Additionally a monitor might have circular references to the monitored object of course, but this might be an other issue.
You could like the object to be monitored in the thread using a WeakReference. This allows the garbage collector to collect and destroy the object. In the thread you would have to check each time if the referenced object still exists every time you perform your checks. If it no longer exists you can safely exit the thread.
As the garbage collector does not immediately destroy objects there may be an unknown time span where the tread is still active but the monitored object is no longer used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With