當前位置: 首頁>>代碼示例>>Java>>正文


Java CancellationException類代碼示例

本文整理匯總了Java中java.util.concurrent.CancellationException的典型用法代碼示例。如果您正苦於以下問題:Java CancellationException類的具體用法?Java CancellationException怎麽用?Java CancellationException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


CancellationException類屬於java.util.concurrent包,在下文中一共展示了CancellationException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: run

import java.util.concurrent.CancellationException; //導入依賴的package包/類
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();
}
 
開發者ID:mgropp,項目名稱:pdfjumbler,代碼行數:21,代碼來源:ProgressDialog.java

示例2: testCancel

import java.util.concurrent.CancellationException; //導入依賴的package包/類
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);
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:22,代碼來源:FutureCallbackTest.java

示例3: testCancelledForkTimedGet

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:RecursiveActionTest.java

示例4: uploadPartsInParallel

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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)));
    }
}
 
開發者ID:IBM,項目名稱:ibm-cos-sdk-java,代碼行數:22,代碼來源:UploadCallable.java

示例5: done

import java.util.concurrent.CancellationException; //導入依賴的package包/類
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());
   } 
}
 
開發者ID:cleitonferreira,項目名稱:LivroJavaComoProgramar10Edicao,代碼行數:17,代碼來源:PrimeCalculator.java

示例6: execute

import java.util.concurrent.CancellationException; //導入依賴的package包/類
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));
                }
            }
        }
    }
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:22,代碼來源:ShellSession.java

示例7: testCancelledForkGetSingleton

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:CountedCompleterTest.java

示例8: testFailOnExceptionFromRun

import java.util.concurrent.CancellationException; //導入依賴的package包/類
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);
}
 
開發者ID:paul-hammant,項目名稱:googles-monorepo-demo,代碼行數:17,代碼來源:AbstractScheduledServiceTest.java

示例9: interruptedDuringReturnValueRetryRetry

import java.util.concurrent.CancellationException; //導入依賴的package包/類
@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();
}
 
開發者ID:google,項目名稱:mug,代碼行數:17,代碼來源:RetryerFunctionalTest.java

示例10: complete

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:31,代碼來源:AbstractFutureBenchmarks.java

示例11: testCancelledForkTimedGetCC

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:ForkJoinPool8Test.java

示例12: pseudoTimedGetUninterruptibly

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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));
  }
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:31,代碼來源:FuturesTest.java

示例13: testCancelledForkGet

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:CountedCompleterTest.java

示例14: testNoOpScheduledExecutorInvokeAll

import java.util.concurrent.CancellationException; //導入依賴的package包/類
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
  }
}
 
開發者ID:paul-hammant,項目名稱:googles-monorepo-demo,代碼行數:22,代碼來源:TestingExecutorsTest.java

示例15: testCancelledForkTimedGetSingleton

import java.util.concurrent.CancellationException; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:ForkJoinTaskTest.java


注:本文中的java.util.concurrent.CancellationException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。