Waiting for a cancelled future to actually finish

前端 未结 3 1124
臣服心动
臣服心动 2021-01-12 17:09

I have a SwingWorker which calls some code that does not check for thread interruption. After the call to worker.cancel(true), the worker.ge

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 17:43

    Inspired by the solution by Paul Blessing I improved it a little to become a class, you can subclass to get the desired funcitonality:

    class AwaitingWorker extends SwingWorker {
    
        private final CountDownLatch actuallyFinishedLatch = new CountDownLatch(1);
    
        /**
         * Override this to do something useful
         */
        protected abstract void performOperation();
    
        @Override
        protected final T doInBackground() throws Exception {
            try {
                return performOperation();
            } finally {
                actuallyFinishedLatch.countDown();
            }
        }
    
        public void awaitActualCompletion() throws InterruptedException {
            actuallyFinishedLatch.await();
        }
    
    }
    

提交回复
热议问题