MultiThreadingConsiderationsInProtege3

From Protege Wiki
Revision as of 11:08, June 2, 2008 by Tredmond (talk | contribs) (New page: == Deadlocks and multi-threaded writes to the knowledge base == Occasionally, developers want to create a background thread which will make changes to the Protege knowledge base. The f...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Deadlocks and multi-threaded writes to the knowledge base

Occasionally, developers want to create a background thread which will make changes to the Protege knowledge base. The first time they try this they usually get deadlocks. Sometimes the deadlock happens right away but in other cases the deadlock occurs at apparently random times. In one case (the OBO converter) the code ran fine as long as the user did not touch the mouse or keyboard. This note explains the source of these deadlocks and how they can be avoided (in the opposite order).


How to avoid the deadlock

The trick to avoiding the deadlock is to have the thread doing the changes to the knowledge base turn off either event generation for the duration of the operation. Often the best choice is to turn off event generation. This code looks like this:

     new Thread(new Runnable() {
        public void run() {
           boolean eventGenerationEnabled = model. setEventGenerationEnabled(false);
           try {

               ... make changes to the knowledge base...
          } finally {
             if (eventGenerationEnabled) {
                model. setEventGenerationEnabled(true);
             }
             reload gui. e.g.
             ProjectManager.getProjectManager().getCurrentProjectView().reloadAll();
          }
       }
    }).start()

The disadvantage of this approach is that after the updates are made to the knowledgebase, the thread must tell all components that are listening to the knowledge base for changes (e.g. the ui) that things have changed and they have not been informed. This is the purpose of the reloadAll() line in the finally clause.

The alternative approach is to turn event dispatch off. This code looks like this:

     new Thread(new Runnable() {
        public void run() {


=== Why does this deadlock happen? ===