Java : CancellationException with Examples
CancellationException (Java SE 20 & JDK 20) API Examples.
You will find code examples on most CancellationException methods.
Summary
try (final var executorService = Executors.newSingleThreadExecutor()) {
final var future = executorService.submit(() -> {
try {
System.out.println("task start");
TimeUnit.SECONDS.sleep(2);
return "abcd";
} catch (InterruptedException e) {
System.out.println("Interrupted!");
return null;
} finally {
System.out.println("task end");
}
});
TimeUnit.SECONDS.sleep(1);
System.out.println("-- get start --");
final var ret = future.get();
System.out.println("-- get end --");
System.out.println("ret = " + ret);
}
// Result
// ↓
//task start
//-- get start --
//task end
//-- get end --
//ret = abcd
try (final var executorService = Executors.newScheduledThreadPool(2)) {
final var future = executorService.submit(() -> {
try {
System.out.println("task start");
TimeUnit.SECONDS.sleep(3);
return "abcd";
} catch (InterruptedException e) {
System.out.println("Interrupted!");
return null;
} finally {
System.out.println("task end");
}
});
executorService.schedule(() -> {
System.out.println("future.cancel");
future.cancel(true);
}, 2, TimeUnit.SECONDS);
try {
System.out.println("-- get start --");
final var ret = future.get();
System.out.println("-- get end --");
System.out.println("ret = " + ret);
} catch (CancellationException e) {
System.out.println("CancellationException!");
}
}
// Result
// ↓
//task start
//-- get start --
//future.cancel
//Interrupted!
//CancellationException!
//task end
Constructors
CancellationException ()
final var e = new CancellationException();
System.out.println(e); // java.util.concurrent.CancellationException
CancellationException (String message)
final var e = new CancellationException("abcd");
System.out.println(e); // java.util.concurrent.CancellationException: abcd
System.out.println(e.getMessage()); // abcd
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.
Related posts
- API Examples
- BlockingQueue
- Callable
- ConcurrentHashMap.KeySetView
- ConcurrentLinkedDeque
- ConcurrentLinkedQueue
- ConcurrentMap
- ConcurrentModificationException
- ConcurrentSkipListSet
- Condition
- CopyOnWriteArrayList
- CopyOnWriteArraySet
- CountDownLatch
- CyclicBarrier
- Exchanger
- Executor
- ExecutorService
- Executors
- Future
- Future.State
- FutureTask
- InterruptedException
- Lock
- Runnable
- Semaphore
- Thread
- ThreadGroup
- ThreadLocal
- TimeUnit