EMF Thread Safety

In my past customer project we designed an RCP application that was supposed to monitorartificial-horizon-attitude-indicator and manage a distributed flight simulation. The simulation consists of dozens of independent simulation nodes that interchange messages and signals over a local network.

Basically the RCP application manages a huge and dynamic model graph that reflects all relevant information of the underlying flight simulation. All that information is displayed simultaneously in multiple views and editors.

The domain model is based on EMF and comprises about 100 classes with hundreds of thousands of runtime instances. The application continuously receives network messages on multiple background jobs and updates parts of the domain model accordingly.

Since a flight simulation is a highly dynamic system with dozens of model updates per second, we stumbled upon two major problems:

  • An unresponsive user interface
  • Concurrent domain model modifications

To avoid unresponsive user interfaces you should:

  • Use the SWT.VIRTUAL style for all your viewers
  • Omit EMF touch events
  • Never block the UI Thread
  • Read the post about EMF.Edit performance

EMF models are not thread-safe by default and writing multithreaded applications is not that simple. The more complex our application became, the more often we got concurrent modification exceptions and had problems with filtering and sorting operations.

As you can see in the table below, the only thread-safe operation on EMF instances is reading a single-valued attribute.

Single-Valued Attribute Multi-Valued Attribute
+ Read – Iterate
– Write – Add/Remove

It’s not obvious that writing a single-valued attribute from multiple threads is forbidden. However attaching an EAdapter in one thread while propagating a set event in another thread fires concurrent modification exceptions as well.

There are two established solutions to avoid multithreading problems in EMF.

EMF Transaction

EMF transaction uses transactional editing domains to synchronize read and write operations on different threads. All write operations are triggered by commands that are executed on the domain’s transactional commandstack.


final TransactionalEditingDomain domain = TransactionalEditingDomain.Registry.INSTANCE.getEditingDomain("instanceName");

domain.getCommandStack().execute(AddCommand.create(...));
domain.getCommandStack().execute(RemoveCommand.create(...));

All Read operations have to run in an exclusive context and the result is passed back as follows:

try {

Double r =(Double)editingDomain.runExclusive(new RunnableWithResult.Impl<Double>() {

  @Override
  public void run() {
    setResult(model.getSignals().stream().mapToDouble(s->s.getValue()).sum());
  }

 label.setText("Sum = " +r);

} catch (InterruptedException e) {}

In addition the framework contains several classes for EMF.edit programming.


//EMF.edit support
viever.setContentProvider(new TransactionalAdapterFactoryContentProvider(domain,af);
viever.setLabelProvider(new TransactionalAdapterFactoryLabelProvider(domain,af);

I gave up figuring out how EMF transaction actually is working behind the scenes. It’s really complex and using the framework requires a consequent usage throughout the entire application. While synchronizing write operations using commands is doable, encapsulating all read operations on a shared editing domain ends up in writing many lines of additional boilerplate code. Especially UI related code becomes quite more complex and it’s very likely that team members simply fade out synchronization when just bringing up a simple info dialog that shows parts of your domain model.

That’s why we decided to use a simpler solution.

Model synchronization on the UI Thread

According to the EMF FAQ, EMF itself does not ensure thread-safety in application model implementations. Data structures are unsynchronized, the expectation is that a complete instance of the model (including resources and resource set, if present) should only be accessed by one thread at a time.

By one thread at one time can also be realized by using always the same single thread. An excellent candidate for such a thread is the UI/Display thread.

The advantage of using this thread is that all model operations triggered from inside the UI thread ( e.g. initializing views, databinding, event handlers ) run faultless without any further synchronization. Since more than 80% of all our application code is running in the UI thread we didn’t have to think about concurrency too much.

However all applications require some long running – mostly IO intensive – background operations that affect the application’s domain model. Fortunately a solution for that is really straightforward.

Write operations in background jobs

Below is an example how to modify the domain model in a background job. By the way never use Java threads directly. Prefer higher a level abstraction like the Eclipse jobs API or executor services.

new Job("Model Update") {

   protected IStatus run(IProgressMonitor monitor) {

       //create model in long running operation
	Signal signal = fetchFromWebserviceOrWhatEver();

       //merge instance in UI thread afterwards
	Display.getDefault().syncExec(()->;model.getSignals().add(signal));

	...

After the long running operation has finished, the new model instance has to be merged immediately. Model updates are pretty short running operations and it’s no problem to run them in the UI thread. Actually this thread is idling and waiting for user input most of its time. However using the display object directly is not recommended because not all OSGI bundles should necessarily have dependencies to SWT.

That’s why we used a simple EMFTRansactionHelper utility class that provides methods to modify EMF models thread-safe. In our RCP application the class is initialized on startup as shown below. For headless unit tests running on the server, this class is initialized with another synchronizer.

public Object start(IApplicationContext context) throws Exception {

 Display display = PlatformUI.createDisplay();
 EMFTransactionHelper.setSynchronizer((runnable) ->display.syncExec(runnable));

The previous example can then be written as:

new Job("Model Append") {

@Override
protected IStatus run(IProgressMonitor monitor) {

 Signal signal = ModelFactory.eINSTANCE.createSignal();
 signal.setName(UUID.randomUUID().toString());
 signal.setValue((int) Math.random());

 EMFTransactionHelper.addElementExclusive(model,ModelPackage.Literals.MODEL__SIGNALS, signal);

Read operations in background jobs

Many long running operations only need read access to the domain model. For instance generating reports or PDF documents. Unlike reading single-valued attributes from multiple threads iterating over multi-valued collections in background jobs is really problematic.

One option is cloning (EcoreUtil.copy()) parts of the application model in the UI thread and use the cloned model for background processing.

If cloning is not possible, the collection must be copied synchronized in the job itself. Here is an example:

new Job("Read Only") {

@Override
protected IStatus run(IProgressMonitor monitor) {

  //clone list thread-safe
  List<Signal> cL = EMFTransactionHelper.cloneCollectionExclusive(model.getSignals);		

  //iterate over clone
  cL.forEach(s-> ...)

Demo Application

The video below shows a very simple application that demonstrates both synchronization techniques. Each viewer contains 10.000 model instances that are modified continuously. The sourcecode is available here.

As you can see, the user interface still reacts very smooth. Both solutions have their pros and cons. For our use case the second solution was the better option. For other uses cases EMF transaction might be the better choice.