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() - startTime);

if (elapsedTime > 1000) {
future.cancel(true);
}
}

The isCancelled() method will return true if the task was canceled before it completes normally:

System.out.println("Task was cancelled: " + future.isCancelled() 
+ " Task is done: " + future.isDone());

The output will be as follows:

Task is in progress ...
Task is in progress ...
...
Task was cancelled: true
Task is done: true

Here are some bonus examples:

  • Using Callable and lambdas:
Future<String> future = executorService.submit(() -> {
return "Hello to you!";
});
  • Getting a Callable that returns null via Executors.callable​(Runnable task):
Callable<Object> callable = Executors.callable(() -> {
System.out.println("Hello to you!");
});

Future<Object> future = executorService.submit(callable);
  • Getting a Callable that returns a result (T) via Executors.callable​(Runnable task, T result):
Callable<String> callable = Executors.callable(() -> {
System.out.println("Hello to you!");
}, "Hi");

Future<String> future = executorService.submit(callable);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.104.183