Thursday, 2 December 2010

org.eclipse.swt.SWTException: Invalid thread access


Eclipse plugin development may introduce new set of exceptions to your life but actually this one is familiar. Just like most other UI architectures SWT, thus eclipse offers a single threaded UI model. Nature of working with in plugins may confuse in which thread you are but eclipse will definitely and politely remind you by raising an "org.eclipse.swt.SWTException: Invalid thread access" exception.

Although most the exceptions you may face during plugin development can be quite tricky, this is one is quite well documented and well known, even in SWT faq.
Briefly the code block needs to deal with the UI thread should be running within the following block:
Display.getDefault().syncExec( new Runnable() {
   public void run() {
      //access UI stuff
   }
});
Simple? Just keep in mind, SWT is a single threaded UI model just like awt, swing or most of the others.