Search code examples
eclipseeclipse-plugineclipse-rcpjobs

Eclipse job with UI access


I have one situation. I have one Eclipse job with following code:

private class ExecutionJob extends Job {
    public static final String MY_FAMILY = "myJobFamily";

    public ExecutionJob(String name) {
        super(name);
    }

    @Override
    protected IStatus run(IProgressMonitor monitor) {
        monitor.beginTask("executing ...... ", IProgressMonitor.UNKNOWN);
        methodForExecution();
        monitor.done();
        return Status.OK_STATUS;
    }

    @Override
    public boolean belongsTo(Object family) {
        return family == MY_FAMILY;
    }
}

And this methodForExecution() has code as below :

public void methodForExecution(){
  PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("view_id");
}

Now, the situation is, job opens up something like progressmonitor, and my method is trying to access UI which is actually behind this job's progressmonitor. And it gives NullPointerException as the progress monitor does not have ActiveWorkbenchWindow.

I can not use UIJob, as I have to execute this methodForExecution() asynchronously. Can someone please help me resolving this.


Solution

  • The code you want to run must run in the UI thead.

    If most of the work in the job is updating the UI and there is no long running non-UI code then you should use UIJob to run this. This is still scheduled as a job but the runInUIThread method is executed in the UI thread.

    If you have a lot of non-UI code especially long running code then use a normal Job but you will have to use Display.asyncExec to run the method in the UI thread:

    Display.getDefault().asyncExec(new Runnable()
      {
        @Override
        public void run()
        {
          methodForExecution();
        }
      });
    

    In Java 8 you could do:

    Display.getDefault().asyncExec(this::methodForExecution);
    

    You can also use syncExec instead of asyncExec to wait for the UI to update.

    If the showView is all you want to do you could just do the asyncExec without using a Job.