简体   繁体   中英

Observer pattern - delete subject (when is the subject deleted by garbage collector)

I have one class subject implementing multiple "observable" interfaces and I need to delete this subject . Because in Java you are not deleting the object yourself (the garbage collector does it for you) I need to delete all references to this object (so I need to unsubscribe from all observers ) is it correct to create method delete which will unsubscribe all observers? Or is there some better way (I tried to google it but I didn't found anything)

In other words could anyone tell me when will be the subject deleted by garbage collector?

It's hard to tell when an object will be deleted by the garbage collector. For me it depends on the GC you are using. So if an object has no reference, indeed it becomes eligible for garbage collection but you won't exactly know when it will actually occur.

Now, to give an answer about your observable pattern, you will need to create a method deleteObservers to remove reference on the subject. I don't know how you implemented the pattern, the Java class Observable has this method but this is deprecated since Java 9.

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