Skip to content

Commit 5dba100

Browse files
committed
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.
1 parent 551f62a commit 5dba100

1 file changed

Lines changed: 7 additions & 5 deletions

File tree

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ public class Context implements Disposable, AutoCloseable {
113113
* False if the context is currently active; true if the context
114114
* has already been disposed, or is in the process of being disposed.
115115
*/
116-
private boolean disposed;
116+
private volatile boolean disposed;
117117

118118
/**
119119
* Creates a new SciJava application context with all available services.
@@ -456,7 +456,7 @@ public boolean isInjectable(final Class<?> type) {
456456

457457
@Override
458458
public void dispose() {
459-
doDispose(true);
459+
if (!disposed) doDispose(true);
460460
}
461461

462462
// -- AutoCloseable methods --
@@ -609,9 +609,11 @@ private String createMissingServiceMessage(
609609
return msg.toString();
610610
}
611611

612-
private synchronized void doDispose(final boolean announce) {
613-
if (disposed) return;
614-
disposed = true;
612+
private void doDispose(final boolean announce) {
613+
synchronized (this) {
614+
if (disposed) return;
615+
disposed = true;
616+
}
615617
CONTEXTS.remove(this);
616618
if (announce) {
617619
final EventService eventService = getService(EventService.class);

0 commit comments

Comments
 (0)