There are problems with the GC when observing the pattern.

In a GC-enabled language, when an observer subscribes to the subject's events, the actual subject receives an observer link.

So, before dropping the observer, he must first unsubscribe. Another reasonable one, because it still refers to the subject, it will never collect garbage.

Usually there are 3 solutions:

  • Manually not signed
  • Weak link.

Both of them cause other problems.

Therefore, usually I do not like to use observer patterns, but I still cannot find a replacement for this.

I mean, this template describes a thing in such a natural way that you can hardly find anything better.

What do you think about this?

+3
3

finalize() Java. finalize() - , (, ), - . , , GC'd , finalize() .

, , - , " ". , ( ) , .

, , , finalize() .

+1
0

, , - . : (1) , ; (2) , (-), , . , , , , , , . , , , .

, , . , , , . Unsubscription, , , . , , , Interlocked.CompareExchange, , .

Note. btw: If the first object contains a link to the second object, the latter will be guaranteed to exist when the finalizer for the first object is launched, but it will not be guaranteed to be in any specific state. The cleanup thread should not try to do anything with it except to unsubscribe.

0
source

Source: https://habr.com/ru/post/1722604/


All Articles