Skip to content

Allow IProgressService.run() to be called from any thread - #4587

Open
fedejeanne wants to merge 1 commit into
eclipse-platform:masterfrom
fedejeanne:progress-service-run-any-thread
Open

fedejeanne wants to merge 1 commit into
eclipse-platform:masterfrom
fedejeanne:progress-service-run-any-thread

Conversation

@fedejeanne

@fedejeanne fedejeanne commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Contributes to: #4202

Problem

IProgressService (in E3 and in E4) extends IRunnableContext. The contract of IRunnableContext#run has no thread restriction. It only says: "If fork is false, the current thread is used to run the runnable". IProgressService narrows this contract with "All methods on the progress service must be called from the UI thread". Its implementations fail when they are called from another thread:

  • the workbench ProgressManager throws an IllegalStateException (since Fix/progress service run #4203; before that, a raw SWTException);
  • the E4 ProgressServiceImpl throws a raw SWTException.

Code that gets "some IRunnableContext" therefore cannot be given the progress service if it might run in a background thread. Clients work around this today. Examples:

Caller Workaround
JDT ReorgCorrectionsSubProcessor, AddGetterSetterAction, OverrideMethodsAction, AddDelegateMethodsAction, ... if (window == null) context = new BusyIndicatorRunnableContext(); (a hidden Display.getCurrent() == null check)
JDT ImportsFix catches a NullPointerException "called from a non-UI thread" and falls back
Team TeamOperation picks a Job-based context instead of the progress service

Why the inconsistency exists

This is my reading of the git history. Confidence is given per point.

  1. 28429cf (2004, "Added IRunnableWithProgressSupport") makes IProgressService extend IRunnableContext. It implements ProgressManager.run with a ProgressMonitorJobsDialog, which creates a Shell in every branch. Sure: the UI-thread dependency came with the first implementation.
  2. 3103abf (2005, Bug 93674) adds the thread wording to IRunnableContext ("the current thread is used"), with no UI restriction. In the same commit, the dialog and window implementations (ProgressMonitorDialog, ApplicationWindow, WizardDialog, IWorkbenchWindow) document that with fork == false "the runnable will run in the UI thread", so they assume a caller on the UI thread. Sure about the text. Medium confidence about the intent.
  3. e5d7e39 (2006, Bug 88325 "IProgressService document enhancements") adds "All methods on the progress service must be called from the UI thread". It is a documentation-only commit, two years after the implementation. In the bug (archived copy), the reporter found "through testing" that run(...) and busyCursorWhile must be called from the UI thread, and asked that this be documented. The fix comment says only that clarifications were added to the Javadoc after a newsgroup discussion about its lack of detail. Nobody discusses the IRunnableContext contract or a reason for the restriction. High confidence: the sentence documents the behavior of the dialog-based implementation as observed in testing. Nothing in the bug shows a decision to narrow the supertype contract. The newsgroup discussion is not linked, so I could not read it.
  4. The sentence was never fully accurate. runInUI(...) has always worked from any thread, because it uses syncExec.

What it does

run(fork, cancelable, runnable) can now be called from any thread, for both the workbench (E3) and the E4 progress service.

Calling thread fork The runnable runs in Progress dialog Cancel button Caller
UI thread any unchanged unchanged unchanged unchanged
other thread false the calling thread none none blocks until done
other thread true a new, separate thread none none blocks until done

From a thread other than the UI thread:

  • No progress dialog opens.
  • The runnable gets a monitor that nobody sees, so progress is not reported and the user cannot cancel. cancelable has no effect that the user can see.
  • Exceptions are reported as ModalContext reports them, the same as for any other IRunnableContext:
    • A RuntimeException or Error arrives wrapped in an InvocationTargetException.
    • An OperationCanceledException arrives as an InterruptedException.

runInUI(...) already worked from any thread. The class Javadoc now says so, with a warning about deadlocks. Nothing changes for calls from the UI thread.

⚠️ Consumer code can change behavior: it can break, or suddenly start to work

Up to now, every released version (since 2004) has thrown an SWTException ("Invalid thread access") when run(...) is called from a thread other than the UI thread. Since #4203 (first shipped in the 4.42 milestones M2 and M3, not yet in a release) the workbench service no longer throws the SWTException. It throws an IllegalStateException instead, with the SWTException as its cause. If #4203 is part of the next release, consumers that catch the SWTException must change anyway, whether or not this PR is merged, because the exception type changed. (The E4 service still throws the raw SWTException.) With this PR such calls succeed. Code that took the old failure into account, deliberately or not, changes behavior without being recompiled:

Kind of consumer code Before After Found in the Eclipse TLPs*
A. Avoids calling run(...) off the UI thread (for example window == null ? new BusyIndicatorRunnableContext() : window, a Display.getCurrent() check, runInUI) works unchanged about 15 workarounds, e.g. in JDT (OverrideMethodsAction, PasteAction, ImportsFix), EGit (CompareUtils), PDE (InputContextManager). None of them reaches run(...) off the UI thread.
B. Catches the exception and falls back to the UI thread to get a progress dialog dialog and cancel button runs in the background thread, no dialog, no cancel button. Nothing reports this. none (3 broad catches only log the error: ProgressServiceView, JDT TestMoveDescriptorAction, JUnit UpdateTestSuite)
C. Asserts the exception (tests) test passes test fails only ProgressServiceTest (#4203), which this PR rewrites
D. Calls run(...) off the UI thread and lets it fail (for example in a Job that only logs the error) no work done, error logged the work is done CopyFilesAndFoldersOperation.copyResourcesInCurrentThread (public API since 3.2)
E. Calls run(...) off the UI thread with a runnable that touches widgets exception before the runnable starts InvocationTargetException (cause SWTException) at the first widget access. Side effects before that point have already happened. none
F. A nested run(...) inside a runnable forked by a UI-thread run(...) exception runs in the same ModalContext thread (as ModalContext does it), with its own monitor. Progress is not shown in the outer dialog, and the outer dialog's cancel is not seen. none (the only indirect chain, via ImportsFix, is stopped by its own guard)
G. Owns a scheduling rule or lock (for example inside a Job with a rule or inside IWorkspace.run) and calls run(true, ...) with a runnable that needs the same rule and does not transfer it (IThreadListener) exception, fails fast hangs forever: the runnable waits for the rule while the caller waits for the runnable. This is the same as with ProgressMonitorDialog or ModalContext when the UI thread owns the rule. Use fork == false. A rule acquired with beginRule can also be moved to the forked thread in IThreadListener#threadChange with IJobManager#transferRule; the rule of the running Job itself cannot be moved. (WorkspaceModifyOperation does not help here: its threadChange throws IllegalStateException when the current Job owns a rule.) none (no run(...) call from a Job or other background thread found)

* Searched: eclipse.platform.ui, eclipse.platform, eclipse.jdt.ui, eclipse.jdt.debug, eclipse.jdt.core, eclipse.pde, EGit, JGit (117 progress-service call sites). Code outside these projects was not checked.

B: the only kind of code that must be rewritten to keep its behavior. None was found in the TLPs. Example:

// Background thread. The author wants a progress dialog.
try {
	PlatformUI.getWorkbench().getProgressService().run(true, true, op);
} catch (SWTException e) { // "Invalid thread access" (since #4203: IllegalStateException)
	display.syncExec(() -> runWithDialog(op)); // fallback: UI thread, dialog, cancel button
}

After this PR the first call succeeds, so the fallback never runs and the user sees no dialog. To keep the dialog, call display.syncExec(() -> runWithDialog(op)) directly, without the try/catch.

D: code that suddenly starts to work. The Javadoc of CopyFilesAndFoldersOperation.copyResourcesInCurrentThread (added in 2005 for Bug 112251, "CopyFilesAndFoldersOperation needs to remove its dependency on the UI Thread") recommends calling it from a WorkspaceJob. From there it has always thrown, because it calls getProgressService().run(false, true, op). With this PR it works as documented. Its overwrite query and error dialogs already use syncExec. A consumer that has called it from a Job for years and only logged the error will now actually copy resources, without changing a line. No caller exists in the TLPs. A generic example of the same pattern:

Job job = Job.create("Update", monitor -> {
	try {
		PlatformUI.getWorkbench().getProgressService().run(false, false, m -> modifyWorkspace(m));
	} catch (Exception e) {
		log(e); // before: always reached ("Invalid thread access"), so no change was ever made
	}
});
job.schedule(); // after: modifyWorkspace() runs

A: workarounds keep working as they are. A consumer that guards the call keeps using its fallback, because the guard is still true off the UI thread. If such a consumer calls run(...) off the UI thread anyway (for example after removing the guard), the call now succeeds without a dialog, as described in D.

G: code that used to fail fast can now hang. Example:

Job job = Job.create("Update", monitor -> {
	try {
		// The job owns the workspace root rule.
		PlatformUI.getWorkbench().getProgressService().run(true, false,
				m -> ResourcesPlugin.getWorkspace().run(w -> modify(w), root, 0, m)); // needs the same rule
	} catch (Exception e) {
		log(e); // before: always reached ("Invalid thread access")
	}
});
job.setRule(root);
job.schedule(); // after: the job hangs. With fork == false it works.

Assessment. Nobody has to rewrite working code, unless it follows pattern B. Pattern B was not found in the TLPs and cannot be ruled out elsewhere. Code following pattern D starts to do work that it never did before. Code following pattern G used to fail fast and can now hang. Please weigh these before merging.

Technical concept

From a thread other than the UI thread (Display.getCurrent() == null), no dialog is involved, and fork keeps the meaning that IRunnableContext gives it:

  • fork == false: the runnable runs in the calling thread ("the current thread is used to run the runnable").
  • fork == true: the runnable runs in a new, separate thread, and the calling thread waits until it has finished. A runnable that implements IThreadListener is told about both thread changes, as ModalContext does it. If the calling thread is interrupted while it waits, the interrupt is passed on to the runnable's thread, the caller keeps waiting, and afterwards it gets its interrupt flag back, unless it throws InterruptedException.
  • As in ModalContext, a caller that already runs in a forked thread (a ModalContext thread, or a thread forked by a progress service) does not fork again. The runnable runs in that thread, so it keeps access to the scheduling rules and locks that thread owns. Both services use one internal JFace implementation (org.eclipse.jface.internal, friend access only), so this also holds when a runnable of the E3 service calls the E4 service, or the other way round.

The separate thread is a plain thread, not a ModalContext thread. A ModalContext thread ends with display.syncExec(...), so a background caller would deadlock while the UI thread waits for it (for example in Job.join() or on a lock). It would also update ModalContext's static modal level from a second thread. A test checks that the call completes while the UI thread is blocked.

Other IRunnableContext implementations are not touched. Only the two progress services change, and only for callers off the UI thread, where they always failed before.

A thread that owns a different Display still takes the dialog path. The Javadoc says "a thread that is not an SWT user-interface thread", which describes this exactly. If the code checked for the workbench display instead, the behavior of the real UI thread would change during startup and shutdown.

The new off-UI-thread tests are registered in ProgressTestSuite, which CI runs as part of UiTestSuite.

How to test

Locally

  1. Start a runtime workbench that includes org.eclipse.ui.examples.job.
  2. Open Window > Show View > Other... > Progress Examples > Progress Service.
  3. Clear call from UI thread. Set a duration of 3000 ms.
  4. Click Run once for each fork/cancelable combination.
  5. Expected for each run: no progress dialog opens, the UI stays responsive, and the Error Log gets no entry. Before this change, each run logged an IllegalStateException.
  6. Select call from UI thread again. Repeat the combinations. Expected: the same behavior as before this change.

Automated

  • AbstractProgressServiceOffUIThreadTest checks the calls from a thread other than the UI thread. ProgressServiceOffUIThreadTest runs it against the E3 service, E4ProgressServiceOffUIThreadTest against the E4 service:
    • With fork == false the runnable runs in the calling thread. With fork == true it runs in a separate thread. In both cases run(...) returns only after the runnable has finished, also when the caller is interrupted while it waits.
    • IThreadListener is notified of the thread changes when fork == true.
    • No dialog opens.
    • Exceptions are mapped as described above (RuntimeException, Error, InvocationTargetException, InterruptedException, OperationCanceledException).
    • The runnable gets a monitor it can use.
    • The call completes while the UI thread is blocked (deadlock regression test).
    • A nested call from a forked ModalContext thread works, for both values of fork.
  • ProgressServiceTest checks the calls from the UI thread, including when the dialog opens.
  • All three test classes are part of ProgressTestSuite.
  • This is how I tested: mvn -Pbuild-individual-bundles verify -pl tests/org.eclipse.ui.tests -am -Dtest=ProgressTestSuite on Windows. ✅ 87 tests, 0 failures, in two runs.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

   867 files  ± 0     867 suites  ±0   58m 19s ⏱️ - 1m 48s
 8 621 tests +54   8 381 ✅ +54  240 💤 ±0  0 ❌ ±0 
21 654 runs  +81  20 981 ✅ +81  673 💤 ±0  0 ❌ ±0 

Results for commit ddbf1b0. ± Comparison against base commit 50268ca.

This pull request removes 2 and adds 56 tests. Note that renamed tests count towards both.
org.eclipse.ui.tests.progress.ProgressServiceTest ‑ testRun_fork_cancelable_runInForeground_callFromNonUIThread_notPumpingUiEvents_throwsIllegalStateException
org.eclipse.ui.tests.progress.ProgressServiceTest ‑ testRun_noFork_cancelable_runInForeground_callFromNonUIThread_notPumpingUiEvents_throwsIllegalStateException
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_callerInterrupted_runnableThrowsInterruptedException_thrownAndFlagCleared
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_callerInterrupted_stillWaitsKeepsInterruptAndInterruptsWorker
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_doesNotDependOnUIThread
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_errorWrappedInInvocationTargetException
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_interruptedExceptionPropagated
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_invocationTargetExceptionPropagated
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_monitorIsUsable
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_noDialogShown
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_notifiesThreadListener
org.eclipse.ui.tests.progress.E4ProgressServiceOffUIThreadTest ‑ testRun_fork_callFromNonUIThread_operationCanceledExceptionMappedToInterruptedException
…

♻️ This comment has been updated with latest results.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Different E3 and E4 worker markers cause nested cross-framework runs to fork again, leaving the runnable without ownership of the outer worker’s scheduling rules or locks.

1 open issue
What changed in this PR

This PR allows E3 and E4 progress services to accept run(...) calls from background threads, addressing the thread-affinity inconsistency discussed in #4202 while preserving existing UI-thread behavior.

Changes:

  • Adds background execution without progress dialogs, including fork, interrupt, exception, and thread-listener handling.
  • Documents the threading contract and updates the example tooltip.
  • Adds E3/E4 regression tests, registers them in the progress suite, and updates bundle dependencies.
File Description
tests/​org.eclipse.ui.tests/​META-INF/​MANIFEST.MF Adds the E4 progress bundle dependency.
tests/​org.eclipse.ui.tests/​Eclipse UI Tests/​org/​eclipse/​ui/​tests/​progress/​ProgressTestSuite.java Registers UI-thread and background-thread service tests.
tests/​org.eclipse.ui.tests/​Eclipse UI Tests/​org/​eclipse/​ui/​tests/​progress/​ProgressServiceTest.java Refines UI-thread dialog detection and waiting.
tests/​org.eclipse.ui.tests/​Eclipse UI Tests/​org/​eclipse/​ui/​tests/​progress/​ProgressServiceOffUIThreadTest.java Applies shared background-thread tests to E3.
tests/​org.eclipse.ui.tests/​Eclipse UI Tests/​org/​eclipse/​ui/​tests/​progress/​E4ProgressServiceOffUIThreadTest.java Applies shared background-thread tests to E4.
tests/​org.eclipse.ui.tests/​Eclipse UI Tests/​org/​eclipse/​ui/​tests/​progress/​AbstractProgressServiceOffUIThreadTest.java Adds shared threading, exception, scheduling-rule, and deadlock regression tests.
examples/​org.eclipse.ui.examples.job/​src/​org/​eclipse/​ui/​examples/​jobs/​views/​ProgressServiceView.java Clarifies background-call behavior in the tooltip.
bundles/​org.eclipse.ui.workbench/​eclipseui/​org/​eclipse/​ui/​progress/​IProgressService.java Documents E3 threading behavior and restrictions.
bundles/​org.eclipse.ui.workbench/​eclipseui/​org/​eclipse/​ui/​internal/​progress/​ProgressManager.java Implements background-thread execution for E3.
bundles/​org.eclipse.e4.ui.progress/​src/​org/​eclipse/​e4/​ui/​progress/​IProgressService.java Documents E4 threading behavior and restrictions.
bundles/​org.eclipse.e4.ui.progress/​src/​org/​eclipse/​e4/​ui/​progress/​internal/​ProgressServiceImpl.java Implements background-thread execution for E4.
bundles/​org.eclipse.e4.ui.progress/​META-INF/​MANIFEST.MF Bumps the bundle version to 0.6.0.

Review effort: Max

@fedejeanne
fedejeanne force-pushed the progress-service-run-any-thread branch from badb645 to 1c0e22d Compare November 24, 2026 07:26
@fedejeanne
fedejeanne requested a balanced review from Copilot November 24, 2026 07:29
@fedejeanne
fedejeanne marked this pull request as ready for review November 24, 2026 07:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Relaxing the public threading contract lets previously rejected off-UI calls execute and may cause scheduling-rule deadlocks, requiring maintainer judgment on third-party compatibility and release risks.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

The workbench and the E4 IProgressService are IRunnableContexts, whose
run() has no thread restriction. Nevertheless, run() fails when it is
called from a thread other than the UI thread, because it always
creates a progress dialog: the workbench service throws an
IllegalStateException, the E4 service an SWTException. Clients that
receive an IRunnableContext and use it from a background thread, for
example from a Job, cannot be given the progress service and have to
work around this.

run() now works from any thread. From the UI thread nothing changes.
From another thread no progress dialog opens and the user cannot
cancel. As IRunnableContext specifies, the runnable runs in the calling
thread when fork is false and in a separate thread when fork is true.
In both cases the calling thread blocks until the runnable has
finished, and exceptions are reported as for any other
IRunnableContext.

The separate thread is a plain thread, not a ModalContext thread: a
ModalContext thread ends with a syncExec, so a background caller would
deadlock while the UI thread waits for it. As in ModalContext, a caller
that already runs in a ModalContext thread or in a thread forked by a
progress service does not fork again, so a nested runnable keeps the
scheduling rules and locks of that thread. Both services share one
internal JFace implementation, so this also holds when a runnable of
one service calls the other.

runInUI() already worked from any thread. The class javadoc now says
so. The new off-UI-thread tests for both services are part of
ProgressTestSuite, so that CI runs them. The UI-thread tests in
ProgressServiceTest now wait for the progress dialog instead of relying
on a fixed delay, so that they are stable in CI.

Contributes to:
eclipse-platform#4202

Assisted-by: Claude Opus 5.5 <noreply@anthropic.com>
@fedejeanne
fedejeanne force-pushed the progress-service-run-any-thread branch from 1c0e22d to ddbf1b0 Compare November 27, 2026 08:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants