Note to self: Events Mostly Don't Leak Memory

Wednesday, April 07, 2010 / Posted by Luke Puplett /

Another note-to-self style blog post in which I write down something that I seem to research and then forget the concrete answer some years later. This one is about the half-myth that events leak memory.

Failing to unsubscribe from events is bad because in some cases it keeps objects from being garbage collected. However, in closely integrated models of classes, it probably won't matter.

The following two UML models show how events may or may not leak.

UML Non-leaky Model UML Leaky Model

On the left hand side, the Application object has a reference to a ViewModel class (the long line), which has a reference to the results of a service query. The ViewModel has subscribed to the CollectionChanged event on a collection exposed by the ServiceQueryResponse class.

Should the ViewModel reference be replaced or nulled in the application (the long line), then the entire object graph will become orphaned; an island to which no references tracks back to any executing code.

Thus, the GC will clean it up.

However, on the right, Application references an 'Other' object - perhaps a service proxy manager which caches the last query - which goes on to reference ServiceQueryResponse.

If the ViewModel reference held by the Application object is nulled, then the ViewModel will not be collected due to the Target reference(s) in the delegates held by the CollectionChanged event.

Of course, if the Application object nulls out its reference to Other, then the whole lot will be collected and the heavyweight ViewModel will free its resources.

This is why I said that close-knit models, its not such a problem. If the events and references are all in a self-contained class or private unit of functionality, its likely that it will become an island.

Just writing this post has actually highlighted an issue I have with caching; my cache doesn't self clear, rather it replaces, so stuff can sit around for ages. And I cannot say for sure what chain of references the cached objects will be maintaining.

The blog post here is helpful in that the author attempts to solve the perceived problem (that doesn't exist) - read the comments.

And similarly on StackOverflow here.

Labels: ,

0 comments:

Post a Comment