Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When observe pattern cause GC problems

In a GC enabled language, when observer subscribes to events of subject, actually subject got a reference of observer.

So before drop an observer, it must un-subscribes first. Other wise, because it's still referenced by subject, it will never be garbage collected.

Normally there are 3 solutions:

  1. Manually un-subscribes
  2. Weak Reference.

Both of them cause other problems.

So usually I don't like to use observer patterns, but I still can not find any replacement for that.

I mean, this pattern describes thing in such a natural way that You could hardly find anything better.

What do you think about it?

like image 740
ablmf Avatar asked May 17 '26 11:05

ablmf


1 Answers

In this scenario, you can use finalize() in Java. finalize() is a bad idea when you have to release a resource (like a DB connection) because some outside system is affected. In your case, the object which installed the observer will be GC'd during the runtime of your app and then, finalize() will be called and it can unsubscribe the observer.

Not exactly what you want but someone must decide "it's okay to unsubscribe, now". That either happens when your subject goes away (but it should already kill all observers) or the object which installed the observer.

If your app terminates unexpectedly, well, it doesn't hurt that finalize() might not be called in this case.

like image 54
Aaron Digulla Avatar answered May 19 '26 03:05

Aaron Digulla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!