Maximilian Koegel co-leads the EclipseSource office and works as a consultant and software engineer for Eclipse technologies. He is an Eclipse expert with a focus in …
EMF Dos and Don´ts #8May 6, 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 #8: Use EContentAdapters Carefully
In my previous blog post, I talked about the EMF notification mechanism and the need to dispose of Adapters correctly. Instead of a simple AdapterImpl receiving notifications from only one EObject, you might want to receive notifications from multiple EObjects. For example, you might want to receive notifications for all EObjects in a ResourceSet, a Resource or a containment tree of a specific EObject. While you could implement this manually quite easily by walking the containment tree and attaching an Adapter to every EObject in the tree, it would be more complicated to update your registered Adapter when the containment tree changes. Imagine that EObjects are disconnected from or added to the containment tree. Every time, you would have to add or remove your Adapter as appropriate. To make this task very simple for you, there is a more powerful adapter in EMF: EContentAdapter.
An EContentAdapter can be attached to a ResourseSet, a Resource or an EObject. If attached to ResourceSet, it will behave as if it is attached to all its Resources and attach to newly added Resources as appropriate. If attached to a Resource, it will behave as if it is attached to all EObjects at the root of the Resource (including newly added EObjects). If it is attached to an EObject, EContentAdapter will attach to it and to all its contained EObjects following the containment tree. Furthermore, it will remove and add itself if EObjects are removed from or added to the containment tree. If any of the EObjects the EContentAdapter is attached to changes it will receive a notification in its notify() method.
In conclusion, adding an EContentAdapter to an EObject with a huge containment tree is an expensive operation in terms of time. Maintaining multiple EContentAdapters is even more time-consuming. If you add a slow operation to the notify method of the EContentAdapter (e.g., refreshing views on each notification), your application might slow down considerably. Of course, there are good use-cases for EContentAdapter but, in general, you should try to limit yourself to adding Adapters to only the EObjects that are of interest for a specific update operation to avoid overhead.
Stay tuned for more Dos and Don´ts in my next blog!