0

I get "Invalid thread access" in below code. I am not sure where I have written wrong code. My main intention to write the code is to just display subtask (what is happening behind the scene) so I have added subtask before method called.

        @Override
        public void handleEvent(Event event) 
        {
            if((event.keyCode == SWT.CR || event.keyCode == 13 || event.type == SWT.Selection) && btnAdd.isEnabled())
            {
                final PreferencesMO permo = new PreferencesMO();
                permo.updatePreferences();
                permo.updateDocumentNumber();
                final ProjectMO pmo = new ProjectMO();
                final CoverSheetMO csmo = new CoverSheetMO();
                final CommonError cmerror = new CommonError();
                final ParameterConfigurationMO pamo  = new ParameterConfigurationMO();
                final SnippetNew s = new SnippetNew();
                final String projName = txtpname.getText();

                Display.getDefault().asyncExec(new Runnable() 
                {
                    public void run() 
                    {
                        try 
                        {
                            new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {

                                @Override
                                public void run(final IProgressMonitor monitor) throws InvocationTargetException,
                                        InterruptedException 
                                {
                                    monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);

                                    monitor.subTask("Connecting to databse...");
                                    for(int i=0;i<=100;i++)
                                    {
                                        s.method1(i);
                                    }
                                    //monitor.worked(1);
                                    try { Thread.sleep(2000); } catch (Exception e) { }

                                    monitor.subTask("Analysing Data...");
                                    try { Thread.sleep(2000); } catch (Exception e) { }


                                    if(!projName.equals(""))
                                    {
                                        monitor.subTask("Updating coversheet ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        cmerror.updateCoverSheetStatusforNewProject();

                                        monitor.subTask("Inserting Project ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        pmo.addProjectManager(projName,"T");

                                        monitor.subTask("Searching Project ID ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        String p_id = pmo.searchprojectID(projName);
                                        permo.insertDocumentNumber(p_id);

                                        monitor.subTask("Inserting data into coversheet ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }
                                        csmo.insertCoversheet(p_id);

                                        pamo.insertParameterConfiguration(p_id);

                                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setText("Demo Tool - "+projName);

                                        IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
                                        AuditLogs view = (AuditLogs) page.findView(AuditLogs.ID);
                                        IEditorPart editorPart = page.getActiveEditor();

                                        StackedLambdaChartInput input = new StackedLambdaChartInput();

                                        AnalysisResult_MetricsChartInput metricsinput = new AnalysisResult_MetricsChartInput();

                                        StackedLambdaChart_HorizantalInput stackedhorizantalinput = new StackedLambdaChart_HorizantalInput();

                                        AnalysisResult_Metrics_HorizantalChartInput metricshorizantalinput = new AnalysisResult_Metrics_HorizantalChartInput();

                                        BarChartInput inpuit = new BarChartInput();

                                        BarChart_HorizantalInput barchart_horizantalinput = new BarChart_HorizantalInput();

                                        AuditLogMO auditlog = new AuditLogMO();

                                        monitor.subTask("Fetching audit logs to display ...");
                                        try { Thread.sleep(2000); } catch (Exception e) { }

                                        java.util.List<java.util.List<String>> auditlogs = auditlog.searchAuditLog(null,null);
                                        view.table(auditlogs);
                                        try
                                         {
                                            handlerService.executeCommand(AuditLogView.ID, new Event());
                                            handlerService.executeCommand(ErrorLogView.ID, new Event());
                                            handlerService.executeCommand(DesignHierarchyHandler.ID, new Event());
                                            if(myeditor != null)
                                            {
                                                if(myeditor instanceof CoverSheet)
                                                {
                                                    handlerService.executeCommand(CoverSheetHandler.ID, new Event());
                                                }
                                                else if(myeditor instanceof ParameterConfigurations)
                                                {
                                                    handlerService.executeCommand(ParameterConfigurationHandler.ID, new Event());
                                                }
                                            }
                                         } 
                                        catch (ExecutionException | NotDefinedException | NotEnabledException | PartInitException| NotHandledException e1)
                                        {
                                            e1.printStackTrace();
                                        }
                                        Constant con = new Constant();
                                        con.createNewProject();
                                    }
                                    //shell.close();


                                    monitor.done();
                                }
                            });
                        } 
                        catch (InvocationTargetException | InterruptedException e) 
                        {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
  • Show us the stack trace and indicate which line in this code it is. – greg-449 Jul 18 '16 at 13:49
  • Possible duplicate of [Invalid Thread Access Error with Java SWT](http://stackoverflow.com/questions/5980316/invalid-thread-access-error-with-java-swt) – Rüdiger Herrmann Jul 18 '16 at 13:50
  • You are trying to access an SWT widget from a background thread. This is not possible. Like most UI toolkits, SWT is single-threaded and widget must only access from within the UI thread. In your case, read the contents of `txtpname` before the Job is scheduled and store it somewhere accessible from within the Job. – Rüdiger Herrmann Jul 18 '16 at 13:52
  • Greg@ When I run it goes till "Analysing Data...". It throws error at "if(!txtpname.getText().equals(""))" condition. I have already commented where i get error. – Rahul Prajapati Jul 18 '16 at 13:56
  • Rüdiger@ I am already reading the content of txtpname before ProgressMonitorDialog called. – Rahul Prajapati Jul 18 '16 at 14:00
  • You are accessing txtpname in Event handler thread , wrap your whole progress monitor dialog in `Display.getDefault().asyncExec( new Runnable() { } );` – SomeDude Jul 18 '16 at 14:03
  • keeping txtpname in another final variable ,it starts working AND wraping whole progress monitor dialog , it also works. but following to the code i have IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); which is getting null. why so ? normally without progress monitor it works. – Rahul Prajapati Jul 18 '16 at 14:20
  • You can't access the workbench page in a background thread. – greg-449 Jul 18 '16 at 14:24
  • how to access then ? because i need to access workbench page and then another methods based on execution of page – Rahul Prajapati Jul 18 '16 at 14:31

2 Answers2

0

You can't access UI code in the background thread used for the IRunnableWithProgress code.

So you must get the values of controls in the UI thread before you run the progress dialog.

You also can't access things like IWorkbenchPage in the background thread. If you want to update UI objects from a non-UI thread, you need to use Display.asyncExec or Display.syncExec to run the updating code in the UI thread.

nitind
  • 19,089
  • 4
  • 34
  • 43
greg-449
  • 109,219
  • 232
  • 102
  • 145
0

Put your progress monitor as below :

Display.getDefault().asyncExec( new Runnable()
{
   IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress()        {

                        @Override
                        public void run(final IProgressMonitor monitor) throws InvocationTargetException,
                                InterruptedException 
                        {
                            monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);

                            monitor.subTask("Connecting to databse...");
                            for(int i=0;i<=100;i++)

}

If you want the workbench page, that also has to be called inside a UI thread like above.

SomeDude
  • 13,876
  • 5
  • 21
  • 44