Eclipse 4 asynchronous processing and the event bus by Lars Vogel

1 minute read

Synchronizing yourself with the user interface thread in Eclipse 4 can be done with the getting an instance of UISynchronize injected and use this class to execute an Runnable in the user interface thread.

@Inject UISynchronize sync; 

But Eclipse 4 provides an even simpler way.

Eclipse 4 provides the IEventBrooker which allows to send events. Your threads can use the IEventBrooker to send event data. Every listener will be automatically called and if you use the UIEventTopic annotation, this method is be automatically called in the user interface thread.

The following shows an example:

// Get the IEventBrooker via DI 
@Inject IEventBroker brooker;

// Somewhere in you code you do something performance intensive

button.addSelectionListener(new SelectionAdapter() { 
	@Override public void widgetSelected(SelectionEvent e) { 
		Runnable runnable = new Runnable() { 
			public void run() { 
				for (int i = 0; i < 10; i++) { 
					try { 
						Thread.sleep(500); 
					} 
					catch (InterruptedException e) { 
						// TODO Auto-generated catch block 
						e.printStackTrace(); 
					} 
					// Send out an event to update the UI 
					brooker.send("update";, i); 
				} 
			} 
		}; 
		new Thread(runnable).start(); 
	} 
});

// More code // ....

// Get notified and sync automatically // with the UI thread

@Inject @Optional public void getEvent(@UIEventTopic(&quot;update&quot;) int i) { 
	// text1 is a SWT Text field 
	text1.setText(String.valueOf(i)); 
	System.out.println(i); 
} 

Have a look at Asynchronous processing in Eclipse 4 and the Eclipse 4 Eventbus for more details.

Updated: