Jonas Helming, Maximilian Koegel and Philip Langer co-lead EclipseSource. They work as consultants and software engineers for building web-based and desktop-based tools. …
EMF Dos and Don´ts #7April 23, 2013 | 3 min Read
EMF is a very powerful framework and with power comes…responsibility. You can achieve great things with a minimum of effort using EMF, but if something goes wrong, you can also spend hours trying to find out why. This blog post is part of a series on things you should do and things you should not do when using EMF. You can use the link to the series pilot to navigate to the start and the link below to navigate to the next blog once it is published.
EMF Dos #7: Remember to dispose of Adapters
EMF features a powerful notification mechanism. To listen to changes in model instances, a.k.a. EObjects, you can attach a so-called Adapter to an EObject. If any of the EObject´s structural features change, a Notification is triggered. In fact, even for non-change events (Notification.isTouch()==true), a Notification is triggered, such as when a proxy is resolved.
To implement an Adapter, you can subclass AdapterImpl and implement the notify() method. On each call of notify, an Adapter will receive a Notification that specifies what happened to the EObject the Adapter is attached to. This will occur with every change and until the Adapter is finally detached. Therefore, it is essential to design a life-cycle for each Adapter that you attach to the model to make sure the Adaptor will eventually be detached. Often it is a good idea to set up a structure wherein the class attaching the Adapter is also responsible for detaching it. A typical use-case would be to attach an Adapter to listen for model changes and update the UI if a change occurs. In this case, the UI class can detach the adapter on dispose().
Adapter-Leaks, which are Adapters that are not disposed of correctly, often cause problems in applications since they waste more and more memory over time and slow down the application by useless calls of notify() of dead adapters. Finally, dead Adapters might even throw exceptions on model changes, e.g., if they try to update a UI that was disposed already, a.k.a. WidgetIsDisposedException.
While it might seem simple to avoid these problems, from my practical experience it is not. I have seen Adapter-Leaks in many EMF-based applications. From my point of view, the only way to avoid them reliably is to establish test cases for correct Adapter removal. Consider you have a UI Test opening an editor that displays some part of your model instance. The test case could simply have an additional assertion, comparing the number of Adapters before opening and after closing the editor.
Stay tuned for more Dos and Don´ts in my next blog!