Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse RCP multithreading

I have an eclipse rcp application. And I have a command when this command is executing. I need to start a thread. After execution of this thread GUI must be updated. But I suppose that this thread or other non-SWT thread cannot update GUI. But it seems reasonable. When I was trying to do that I got Exception in thread "Thread-5" org.eclipse.swt.SWTException: Invalid thread access. How I can make this goal?

like image 824
itun Avatar asked Dec 27 '22 00:12

itun


2 Answers

Using SWT you need to have anything that updates the GUI be done on the main thread, or in Eclipse, it's called the UI thread (it's the same thread). You are getting this error because you are trying to access an SWT object on another thread. Consider using Display.syncExec() or Display.asyncExec() to move the SWT related processing to the main thread. You want to be careful with syncExec() that you don't cause a deadlock.

like image 127
Francis Upton IV Avatar answered Jan 09 '23 19:01

Francis Upton IV


Normally I would not use java.lang.Thread in an RCP application, since Eclipse provides different level of abstraction and control over long running operations via the Jobs API (https://eclipse.org/articles/Article-Concurrency/jobs-api.html). Here is a solution for your problem:

    Runnable uiUpdater = new Runnable() {
        public void run() {
            // update SWT UI safely here
            // ...
        }
    };
    Job longRunningOperation = new Job("My command") {
        protected IStatus run(IProgressMonitor monitor) {
            // some time consuming code here        
            // ...      
            Display.getDefault().asyncExec(uiUpdater);
            return Status.OK_STATUS;
        }
    };
    longRunningOperation.schedule();
like image 35
Dinko Ivanov Avatar answered Jan 09 '23 20:01

Dinko Ivanov