public static boolean run(SwingWorker<?,?> worker, Frame parent) throws Exception { ProgressDialog dialog = new ProgressDialog(parent, worker); worker.execute(); dialog.setVisible(true); try { worker.get(); } catch (ExecutionException e) { if (e.getCause() instanceof CancellationException) { return false; } else if (e.getCause() instanceof Exception) { throw (Exception)e.getCause(); } else { // ?!? throw new AssertionError(e); } } return !worker.isCancelled(); }
public void testCancel() { SettableFuture<String> f = SettableFuture.create(); FutureCallback<String> callback = new FutureCallback<String>() { private boolean called = false; @Override public void onSuccess(String result) { fail("Was not expecting onSuccess() to be called."); } @Override public synchronized void onFailure(Throwable t) { assertFalse(called); assertThat(t).isInstanceOf(CancellationException.class); called = true; } }; addCallback(f, callback, directExecutor()); f.cancel(true); }
/** * timed get of a forked task throws exception when task cancelled */ public void testCancelledForkTimedGet() { RecursiveAction a = new CheckedRecursiveAction() { protected void realCompute() throws Exception { FibAction f = new FibAction(8); assertTrue(f.cancel(true)); assertSame(f, f.fork()); try { f.get(LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (CancellationException success) { checkCancelled(f); } }}; testInvokeOnPool(mainPool(), a); }
/** * Submits a callable for each part to upload to our thread pool and records its corresponding Future. */ private void uploadPartsInParallel(UploadPartRequestFactory requestFactory, String uploadId) { Map<Integer,PartSummary> partNumbers = identifyExistingPartsForResume(uploadId); while (requestFactory.hasMoreRequests()) { if (threadPool.isShutdown()) throw new CancellationException("TransferManager has been shutdown"); UploadPartRequest request = requestFactory.getNextUploadPartRequest(); if (partNumbers.containsKey(request.getPartNumber())) { PartSummary summary = partNumbers.get(request.getPartNumber()); eTagsToSkip.add(new PartETag(request.getPartNumber(), summary .getETag())); transferProgress.updateProgress(summary.getSize()); continue; } futures.add(threadPool.submit(new UploadPartCallable(s3, request))); } }
protected void done() { getPrimesJButton.setEnabled(true); // enable Get Primes button cancelJButton.setEnabled(false); // disable Cancel button try { // retrieve and display doInBackground return value statusJLabel.setText("Found " + get() + " primes."); } catch (InterruptedException | ExecutionException | CancellationException ex) { statusJLabel.setText(ex.getMessage()); } }
public static ExitStatus execute(final ExecutionEnvironment env, final String command) throws IOException, CancellationException { while (true) { final ShellProcess process = startProcessIfNeeded(env); if (process == null) { continue; } synchronized (process) { if (ProcessUtils.isAlive(process.process)) { try { ExitStatus result = executeSync(process, env, command); if (result != null) { return result; } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); return new ExitStatus(-1, null, MiscUtils.getMessageAsList(ex)); } } } } }
/** * get of a forked task throws exception when task cancelled */ public void testCancelledForkGetSingleton() { ForkJoinTask a = new CheckedRecursiveAction() { protected void realCompute() throws Exception { CCF f = new LCCF(8); assertTrue(f.cancel(true)); assertSame(f, f.fork()); try { f.get(); shouldThrow(); } catch (CancellationException success) { checkCancelled(f); } }}; testInvokeOnPool(singletonPool(), a); }
public void testFailOnExceptionFromRun() throws Exception { TestService service = new TestService(); service.runException = new Exception(); service.startAsync().awaitRunning(); service.runFirstBarrier.await(); service.runSecondBarrier.await(); try { future.get(); fail(); } catch (CancellationException expected) { } // An execution exception holds a runtime exception (from throwables.propogate) that holds our // original exception. assertEquals(service.runException, service.failureCause()); assertEquals(service.state(), Service.State.FAILED); }
@Test public void interruptedDuringReturnValueRetryRetry() throws InterruptedException, IOException { Retryer.ForReturnValue<String> forReturnValue = retryer.uponReturn("bad", asList(Delay.ofMillis(0), Delay.ofMillis(0))); when(blockedAction.result()).thenReturn("bad").thenReturn("fixed"); CompletionStage<String> stage = forReturnValue.retry(blockedAction::blockOnSecondTime, executor); blockedAction.retryStarted.await(); blockedAction.interrupt(); // Sadly cancellation from inner future doesn't propagate to outer. ExecutionException exception = assertThrows(ExecutionException.class, () -> stage.toCompletableFuture().get()); assertThat(exception.getCause()).isInstanceOf(CancellationException.class); assertThat(exception.getCause().getCause()).isInstanceOf(InterruptedException.class); assertThat(exception.getCause().getSuppressed()).isEmpty(); }
/** * Implementation of completing a task. Either {@code v} or {@code t} will * be set but not both. The {@code finalState} is the state to change to * from {@link #RUNNING}. If the state is not in the RUNNING state we * return {@code false} after waiting for the state to be set to a valid * final state ({@link #COMPLETED}, {@link #CANCELLED}, or {@link * #INTERRUPTED}). * * @param v the value to set as the result of the computation. * @param t the exception to set as the result of the computation. * @param finalState the state to transition to. */ private boolean complete(@Nullable V v, @Nullable Throwable t, int finalState) { boolean doCompletion = compareAndSetState(RUNNING, COMPLETING); if (doCompletion) { // If this thread successfully transitioned to COMPLETING, set the value // and exception and then release to the final state. this.value = v; // Don't actually construct a CancellationException until necessary. this.exception = ((finalState & (CANCELLED | INTERRUPTED)) != 0) ? new CancellationException("Future.cancel() was called.") : t; releaseShared(finalState); } else if (getState() == COMPLETING) { // If some other thread is currently completing the future, block until // they are done so we can guarantee completion. acquireShared(-1); } return doCompletion; }
/** * timed get of a forked task throws exception when task cancelled */ public void testCancelledForkTimedGetCC() throws Exception { ForkJoinTask a = new CheckedRecursiveAction() { protected void realCompute() throws Exception { CCF f = new LCCF(null, 8); assertTrue(f.cancel(true)); assertSame(f, f.fork()); try { f.get(LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (CancellationException success) { checkCancelled(f); } }}; checkInvoke(a); }
/** * Very rough equivalent of a timed get, produced by calling the no-arg get method in another * thread and waiting a short time for it. * * <p>We need this to test the behavior of no-arg get methods without hanging the main test thread * forever in the case of failure. */ @CanIgnoreReturnValue @GwtIncompatible // threads static <V> V pseudoTimedGetUninterruptibly(final Future<V> input, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { ExecutorService executor = newSingleThreadExecutor(); Future<V> waiter = executor.submit(new Callable<V>() { @Override public V call() throws Exception { return input.get(); } }); try { return getUninterruptibly(waiter, timeout, unit); } catch (ExecutionException e) { propagateIfInstanceOf(e.getCause(), ExecutionException.class); propagateIfInstanceOf(e.getCause(), CancellationException.class); throw failureWithCause(e, "Unexpected exception"); } finally { executor.shutdownNow(); // TODO(cpovirk: assertTrue(awaitTerminationUninterruptibly(executor, 10, SECONDS)); } }
/** * get of a forked task throws exception when task cancelled */ public void testCancelledForkGet() { ForkJoinTask a = new CheckedRecursiveAction() { protected void realCompute() throws Exception { CCF f = new LCCF(8); assertTrue(f.cancel(true)); assertSame(f, f.fork()); try { f.get(); shouldThrow(); } catch (CancellationException success) { checkCancelled(f); } }}; testInvokeOnPool(mainPool(), a); }
public void testNoOpScheduledExecutorInvokeAll() throws ExecutionException, InterruptedException { ListeningScheduledExecutorService executor = TestingExecutors.noOpScheduledExecutor(); taskDone = false; Callable<Boolean> task = new Callable<Boolean>() { @Override public Boolean call() { taskDone = true; return taskDone; } }; List<Future<Boolean>> futureList = executor.invokeAll( ImmutableList.of(task), 10, TimeUnit.MILLISECONDS); Future<Boolean> future = futureList.get(0); assertFalse(taskDone); assertTrue(future.isDone()); try { future.get(); fail(); } catch (CancellationException e) { // pass } }
/** * timed get of a forked task throws exception when task cancelled */ public void testCancelledForkTimedGetSingleton() throws Exception { RecursiveAction a = new CheckedRecursiveAction() { protected void realCompute() throws Exception { AsyncFib f = new AsyncFib(8); assertTrue(f.cancel(true)); assertSame(f, f.fork()); try { f.get(LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (CancellationException success) { checkCancelled(f); } }}; testInvokeOnPool(singletonPool(), a); }
/** * 线程池内异常处理 * @param r * @param t */ private void printException(Runnable r, Throwable t) { if (t == null && r instanceof Future<?>) { try { Future<?> future = (Future<?>) r; if (future.isDone()) future.get(); } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); // ignore/reset } } if (t != null) logger.error(t.getMessage(), t); }
private void handleWatchRepositoryResult( CompletableFuture<com.linecorp.centraldogma.common.Revision> future, AsyncMethodCallback resultHandler) { future.handle(voidFunction((res, cause) -> { if (cause == null) { final WatchRepositoryResult wrr = new WatchRepositoryResult(); wrr.setRevision(convert(res)); resultHandler.onComplete(wrr); } else if (cause instanceof CancellationException) { if (watchService.isServerStopping()) { resultHandler.onError(new CentralDogmaException(ErrorCode.SHUTTING_DOWN)); } else { resultHandler.onComplete(CentralDogmaConstants.EMPTY_WATCH_REPOSITORY_RESULT); } } else { logAndInvokeOnError("watchRepository", resultHandler, cause); } })); }
public static <TResult> Task<TResult> call(final Callable<TResult> callable, Executor executor, final CancellationToken ct) { final TaskCompletionSource tcs = create(); executor.execute(new Runnable() { public void run() { if (ct == null || !ct.isCancellationRequested()) { try { tcs.setResult(callable.call()); return; } catch (CancellationException e) { tcs.setCancelled(); return; } catch (Exception e2) { tcs.setError(e2); return; } } tcs.setCancelled(); } }); return tcs.getTask(); }
/** * timed get of a forked task throws exception when task cancelled */ public void testCancelledForkTimedGetSingleton() throws Exception { ForkJoinTask a = new CheckedRecursiveAction() { protected void realCompute() throws Exception { CCF f = new LCCF(8); assertTrue(f.cancel(true)); assertSame(f, f.fork()); try { f.get(LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (CancellationException success) { checkCancelled(f); } }}; testInvokeOnPool(singletonPool(), a); }
private void runTaskTest(Callable<Task<?>> callable) { try { Task<?> task = callable.call(); task.waitForCompletion(); if (task.isFaulted()) { Exception error = task.getError(); if (error instanceof RuntimeException) { throw (RuntimeException) error; } throw new RuntimeException(error); } else if (task.isCancelled()) { throw new RuntimeException(new CancellationException()); } } catch (Exception e) { throw new RuntimeException(e); } }
@Override protected void afterExecute(Runnable runnable, Throwable throwable) { super.afterExecute(runnable, throwable); if (throwable == null && runnable instanceof Future<?>) { Future<?> future = (Future<?>) runnable; try { // Not all Futures will be done, e.g. when used with scheduledAtFixedRate if (future.isDone()) { future.get(); } } catch (CancellationException ce) { // Cancellation exceptions are okay, we expect them to happen sometimes } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (throwable == REVIVE_THREAD_EXCEPTION) { // Re-throwing this exception will kill the thread and cause // ScheduledThreadPoolExecutor to // spawn a new thread. throw (RuntimeException) throwable; } else if (throwable != null) { handleException(throwable); } }
@Test(expected = CancellationException.class) public void run_Cancelled_ThrowsException() { AtomicBoolean executed = new AtomicBoolean(false); ScheduledTask task = new ScheduledTask(0, null, true, 0, () -> { executed.set(true); }); task.cancel(); task.run(); }
public void testCancel_notDoneNoInterrupt() throws Exception { Future<?> future = newFutureInstance(); assertTrue(future.cancel(false)); assertTrue(future.isCancelled()); assertTrue(future.isDone()); try { future.get(); fail("Expected CancellationException"); } catch (CancellationException e) { assertNotNull(e.getCause()); } }
public void testCancel_resultCancelsInner() throws Exception { SettableFuture<Object> async = SettableFuture.create(); SettableFuture<Object> inner = SettableFuture.create(); async.setFuture(inner); async.cancel(false); assertTrue(inner.isCancelled()); assertFalse(inner.wasInterrupted()); try { inner.get(); fail("Expected CancellationException"); } catch (CancellationException expected) { /* expected */ } }
private synchronized R doGet(Long timeoutMillis) throws ExecutionException, InterruptedException, TimeoutException { if (assertBackgroundThread && !isDone()) { Util.assertBackgroundThread(); } if (isCancelled) { throw new CancellationException(); } else if (loadFailed) { throw new ExecutionException(exception); } else if (resultReceived) { return resource; } if (timeoutMillis == null) { waiter.waitForTimeout(this, 0); } else if (timeoutMillis > 0) { waiter.waitForTimeout(this, timeoutMillis); } if (Thread.interrupted()) { throw new InterruptedException(); } else if (loadFailed) { throw new GlideExecutionException(exception); } else if (isCancelled) { throw new CancellationException(); } else if (!resultReceived) { throw new TimeoutException(); } return resource; }
@Test public void otherOnCompleteCompletable() { PublishSubject<Integer> pp = PublishSubject.create(); PublishSubject<Integer> source = PublishSubject.create(); TestObserver<Integer> ts = source.single(-99).takeUntil(pp.ignoreElements()) .test(); pp.onComplete(); ts.assertFailure(CancellationException.class); }
private void assertDataSourceCancelled() { verify(mDataSubscriber).onFailure(mListDataSource); verifyNoMoreInteractions(mDataSubscriber); assertFalse(mListDataSource.hasResult()); assertTrue(mListDataSource.hasFailed()); assertTrue(mListDataSource.isFinished()); assertTrue(mListDataSource.getFailureCause() instanceof CancellationException); assertNull(mListDataSource.getResult()); }
public void testListenersNotifiedOnError() throws Exception { final CountDownLatch successLatch = new CountDownLatch(1); final CountDownLatch listenerLatch = new CountDownLatch(1); ExecutorService exec = Executors.newCachedThreadPool(); future.addListener(new Runnable() { @Override public void run() { listenerLatch.countDown(); } }, exec); new Thread(new Runnable() { @Override public void run() { try { future.get(); } catch (CancellationException expected) { successLatch.countDown(); } catch (Exception ignored) { // No success latch count down. } } }).start(); future.cancel(true); assertTrue(future.isCancelled()); assertTrue(future.isDone()); assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS)); assertTrue(listenerLatch.await(200, TimeUnit.MILLISECONDS)); latch.countDown(); exec.shutdown(); exec.awaitTermination(100, TimeUnit.MILLISECONDS); }
/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { LogUtils.error(LOG_TAG, e.toString()); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }
public void testFutureGetThrowsCancellationIfOutputCancelled() throws Exception { inputFuture.set(SLOW_OUTPUT_VALID_INPUT_DATA); outputFuture.cancel(true); // argument is ignored try { resultFuture.get(); fail("Result future must throw CancellationException" + " if function output future is cancelled."); } catch (CancellationException expected) {} }
@Override protected Pair<String, Object> evaluate(String expression, DebuggerEngine engine) throws CancellationException { Session session = engine.lookupFirst(null, Session.class); if (engine != session.getEngineForLanguage(JSUtils.JS_STRATUM)) { return null; } JPDADebugger d = engine.lookupFirst(null, JPDADebugger.class); if (d == null) { return null; } CallStackFrame frame = d.getCurrentCallStackFrame(); if (frame == null) { return null; } String toolTipText; JSVariable jsresult = null; try { Variable result = DebuggerSupport.evaluate(d, frame, expression); if (result == null) { throw new CancellationException(); } if (result instanceof ObjectVariable) { jsresult = JSVariable.createIfScriptObject(d, (ObjectVariable) result, expression); } if (jsresult != null) { toolTipText = expression + " = " + jsresult.getValue(); } else { toolTipText = expression + " = " + DebuggerSupport.getVarValue(d, result); } } catch (InvalidExpressionException ex) { toolTipText = expression + " = >" + ex.getMessage () + "<"; } return Pair.of(toolTipText, (Object) jsresult); }
/** * Transaction cancellation is a heavyweight operation. We only support cancelation of a locked transaction * and return false for everything else. Cancelling such a transaction will result in all transactions in the * batch to be cancelled. * * @param tx Backend shared transaction * @param frontendTx * @param isOpen indicator whether the transaction was already closed */ synchronized void cancelTransaction(final PingPongTransaction tx, final DOMDataReadWriteTransaction frontendTx) { // Attempt to unlock the operation. final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null); Verify.verify(lockedMatch, "Cancelling transaction %s collided with locked transaction %s", tx, lockedTx); // Cancel the backend transaction, so we do not end up leaking it. final boolean backendCancelled = tx.getTransaction().cancel(); if (failed) { // The transaction has failed, this is probably the user just clearing up the transaction they had. We have // already cancelled the transaction anyway, return; } else if (!backendCancelled) { LOG.warn("Backend transaction cannot be cancelled during cancellation of {}, attempting to continue", tx); } // We have dealt with canceling the backend transaction and have unlocked the transaction. Since we are still // inside the synchronized block, any allocations are blocking on the slow path. Now we have to decide the fate // of this transaction chain. // // If there are no other frontend transactions in this batch we are aligned with backend state and we can // continue processing. if (frontendTx.equals(tx.getFrontendTransaction())) { LOG.debug("Cancelled transaction {} was head of the batch, resuming processing", tx); return; } // There are multiple frontend transactions in this batch. We have to report them as failed, which dooms this // transaction chain, too. Since we just came off of a locked transaction, we do not have a ready transaction // at the moment, but there may be some transaction in-flight. So we proceed to shutdown the backend chain // and mark the fact that we should be turning its completion into a failure. deadTx = new SimpleImmutableEntry<>(tx, new CancellationException("Transaction " + frontendTx + " canceled").fillInStackTrace()); delegate.close(); }
public void testFutureCancelBeforeInputCompletion() throws Exception { assertTrue(resultFuture.cancel(true)); assertTrue(resultFuture.isCancelled()); assertTrue(inputFuture.isCancelled()); assertFalse(outputFuture.isCancelled()); try { resultFuture.get(); fail("Result future is cancelled and should have thrown a" + " CancellationException"); } catch (CancellationException expected) {} }
@Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { if (cancelled.get()) { throw new CancellationException(); } long millis = TimeUnit.MILLISECONDS.convert(timeout, unit); t.waitFinished(millis); if (cancelled.get()) { throw new CancellationException(); } return null; }
@Override public void run() { if (isCancelled()) { return; } if (delegate instanceof AbstractFuture) { AbstractFuture<? extends V> other = (AbstractFuture<? extends V>) delegate; value = other.value; throwable = other.throwable; mayInterruptIfRunning = other.mayInterruptIfRunning; state = other.state; notifyAndClearListeners(); return; } /* * Almost everything in GWT is an AbstractFuture (which is as good as TrustedFuture under * GWT). But ImmediateFuture and UncheckedThrowingFuture aren't, so we still need this case. */ try { forceSet(getDone(delegate)); } catch (ExecutionException exception) { forceSetException(exception.getCause()); } catch (CancellationException cancellation) { cancel(false); } catch (Throwable t) { forceSetException(t); } }
private void verifyNotStopped() throws CancellationException { synchronized (LoaderTask.this) { if (mStopped) { throw new CancellationException("Loader stopped"); } } }
public void testCancel_innerCancelsAsync() throws Exception { SettableFuture<Object> async = SettableFuture.create(); SettableFuture<Object> inner = SettableFuture.create(); async.setFuture(inner); inner.cancel(true); assertTrue(async.isCancelled()); try { async.get(); fail("Expected CancellationException"); } catch (CancellationException expected) { /* expected */ } }
public T get() throws CancellationException, InterruptedException, ExecutionException { try { return get(0, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { throw new Error(e); } }