Multi-threading and yFiles' graph structures

Questions & Answers

Summary

When working with yFiles graph structures in multi-threaded applications some effort has to be put into proper synchronization.
For a better user experience, please go to the integrated documentation viewer to read this article.

Description

In general, yFiles' graph structures, its layout algorithms, and its visualization framework are not thread-safe. It is your responsibility to add synchronization where necessary. However, for most use cases, doing things in the right thread is sufficient.

Typically, there is (at least) one graph that is displayed to a user, most probably using a Graph2DView, and modified concurrently. Since Graph2DView is a SWING component, the general rule for threads and SWING components applies: "All modifications have to be done within SWING's event dispatch thread (EDT)." Aside from the obvious structural modifications such as adding or deleting elements to or from the graph, this includes any aspects that affect the graph's visual representation such as any modifications made to node or edge realizers.
java.awt.EventQueue's static methods invokeAndWait(Runnable) and invokeLater(Runnable) may be used to enforce the above rule.

Another common use case is to calculate graph layouts in a separate thread. "How to layout a graph in a separate thread" describes the basic steps necessary for that approach. In summary, these steps are

  1. create a copy of your main graph
  2. calculate a layout for the copy in a separate thread
  3. update your main graph according to the geometry data of the copy
Obviously, step 3 needs to be done in a synchronized manner (e.g. by doing the update in the EDT, if your main graph is displayed). However, that is not quite enough. Copying a graph is not an atomic operation, concurrent modifications to the original can cause all kinds of problems. Therefore, step 1 needs to be done in a synchronized manner, too (e.g. by creating the copy in the EDT, if your main graph is displayed).
Using CopiedLayoutGraph, step 1 (and step 3) can be accomplished in a convenient way. For the methods provided by this class to work properly, the original graph may not be (structurally) modified while its copy is in use.

In a nutshell, it is important to synchronize all modifications made to a graph. For graphs that are displayed using Graph2DView this means handling all changes in the EDT. Additionally, when calculating layouts in a separate thread using CopiedLayoutGraph, the original graph may not be modified while the copy is in use.

Categories this article belongs to:
yFiles for Java > Other
Applies to:
yFiles for Java 2: 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10, 2.11, 2.12, 2.13, 2.14, 2.15, 2.16, 2.17, 2.18
Keywords:
layout - thread - threading - multi threading - multi-threading - multithreading