本文整理汇总了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();
}
示例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);
}
示例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);
}
示例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)));
}
}
示例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());
}
}
示例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));
}
}
}
}
}
示例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);
}
示例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);
}
示例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();
}
示例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;
}
示例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);
}
示例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));
}
}
示例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);
}
示例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
}
}
示例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);
}