Skip to Content
Java Coding Problems
book

Java Coding Problems

by Anghel Leonard
September 2019
Intermediate to advanced
816 pages
18h 47m
English
Packt Publishing
Content preview from Java Coding Problems

Canceling a Future

A Future can be canceled. This is accomplished using the cancel​(boolean mayInterruptIfRunning) method. If we pass it as true, the thread that executes the task is interrupted, otherwise, the thread may complete the task. This method returns true if the task was successfully canceled, otherwise it returns false (typically, because it has already completed normally). Here is a simple example that cancels a task if it takes more than one second to run:

long startTime = System.currentTimeMillis();Future<String> future = executorService.submit(() -> {  Thread.sleep(3000);  return "Task completed";});while (!future.isDone()) {  System.out.println("Task is in progress ...");  Thread.sleep(100); long elapsedTime = (System.currentTimeMillis() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Coding Problems - Second Edition

Java Coding Problems - Second Edition

Anghel Leonard
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781789801415Supplemental Content