Search code examples
garbage-collectionobserver-pattern

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?


Solution

  • 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.