Commits

ship-it committed e62e4c9

Fixed concurrency issue where interrupt() could NPE after task is completed.

  • Participants
  • Parent commits f96b79d

Comments (0)

Files changed (1)

src/main/java/com/atlassian/utils/process/LatchedRunnable.java

 import java.util.Stack;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 
 /**
  * Date: 16/07/2008
 public abstract class LatchedRunnable implements Runnable {
     private static Logger log = Logger.getLogger(LatchedRunnable.class);
     private CountDownLatch latch = new CountDownLatch(1);
-    private Thread runner;
     private boolean cancelled;
     private Stack<?> ndcStack = NDC.cloneStack();
     protected String name;
 
+    private final AtomicReference<Thread> runner = new AtomicReference<Thread>();
+
     protected LatchedRunnable() {
         this.name = "LatchedRunnable";
     }
     public final void run() {
         try {
             NDC.inherit(ndcStack);
-            runner = Thread.currentThread();
+            runner.set(Thread.currentThread());
             doTask();
         } finally {
             latch.countDown();
             NDC.remove();
             // release the runner thread, we're done with it.
-            runner = null;
+            runner.set(null);
         }
     }
 
 
     protected abstract void doTask();
 
-
     public void interrupt() {
-        if (runner != null) {
-            runner.interrupt();
+        Thread runnerThread = this.runner.get();
+        if (runnerThread != null) {
+            runnerThread.interrupt();
         }
     }