Skip to content

Commit 680d702

Browse files
ctruedenclaude
andcommitted
Make Context.doDispose() less deadlock-prone
We only need to hold the lock for the duration of the disposed flag check; holding it for the entirety of the disposal operation could deadlock in some circumstances, such as when context.dispose() is called from within a WindowEvent listener's windowClosing method. As per scijava/scijava-common@5dba100. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 7f4e5fa commit 680d702

1 file changed

Lines changed: 18 additions & 7 deletions

File tree

‎context/src/main/java/org/scijava/context/Context.java‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public class Context implements Disposable, AutoCloseable {
8989
/** Plugin discovery, from the annotation index. Built on first use. */
9090
private IndexDiscoverer<Plugin> pluginDiscoverer;
9191

92-
private boolean disposed;
92+
private volatile boolean disposed;
9393

9494
private Context(final List<Provider<Service>> providers) {
9595
this.providers = providers;
@@ -282,20 +282,31 @@ public synchronized boolean isDisposed() {
282282
* </p>
283283
*/
284284
@Override
285-
public synchronized void dispose() {
285+
public void dispose() {
286286
if (disposed) return;
287-
disposed = true;
287+
final List<Service> toDispose;
288+
synchronized (this) {
289+
if (disposed) return;
290+
disposed = true;
291+
// NB: Snapshot and clear under the lock, but dispose the services
292+
// themselves outside of it. A service's dispose() may block on
293+
// another thread (e.g. a Swing UI's disposal round-tripping through
294+
// the EDT); holding this context's lock for that entire time would
295+
// risk deadlock against any other thread synchronizing on this
296+
// context, such as one blocked inside optionalService(...).
297+
toDispose = new ArrayList<>(created);
298+
created.clear();
299+
byRequestedType.clear();
300+
}
288301
final List<Throwable> failures = new ArrayList<>();
289-
for (int i = created.size() - 1; i >= 0; i--) {
302+
for (int i = toDispose.size() - 1; i >= 0; i--) {
290303
try {
291-
created.get(i).dispose();
304+
toDispose.get(i).dispose();
292305
}
293306
catch (final Throwable exc) {
294307
failures.add(exc);
295308
}
296309
}
297-
created.clear();
298-
byRequestedType.clear();
299310
// NB: closing the bus is what frees services from arranging their own
300311
// unsubscription.
301312
events.close();

0 commit comments

Comments
 (0)