September 2019
Intermediate to advanced
816 pages
18h 47m
English
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() ...