HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Multi-threading / ExecutorService – Cancel a task in executor

ExecutorService – Cancel a task in executor

Learn to cancel a task submitted to an executor which is still has to be executed and has not been completed yet using cancel() method of Future object which allows you to make the cancellation operation.

1. Future cancel() API

The Future.cancel(mayInterruptIfRunning) method takes one argument of type boolean.

boolean cancel(boolean mayInterruptIfRunning);

Depending on the value of mayInterruptIfRunning and the status of the task submitted to executor, the behavior of this method is different:

  • If the task has finished or has been canceled earlier, or it can’t be cancelled due to any other reason, the method will return the false value and the task won’t be canceled.
  • If the task is waiting in the executor to begin execution, the task will be canceled and will never begin its execution. Method will return true.
  • If the task is already running and value of mayInterruptIfRunning parameter is true, task will be canceled.
  • If the task is already running and value of mayInterruptIfRunning parameter is false, task will NOT be canceled.

2. Task cancellation example

In this java program, we have task which will be executed after a minute from scheduled time. After scheduling, we check the status of task using isDone() method which return false which task has not completed yet.

Then we cancel the task, and check the status of task using isCancelled() and isDone() methods, both.

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Main 
{
	public static void main(String[] args) throws InterruptedException, ExecutionException 
	{
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
		
		LocalDateTime now = LocalDateTime.now();
	        LocalDateTime afterOneMinute = now.plusMinutes(1);
	 
	        Duration duration = Duration.between(now, afterOneMinute);
	        long delay = Math.abs(duration.toMillis());
	    
	        System.out.println("Task scheduled at : "+ LocalDateTime.now());
		
	        ScheduledFuture<String> result = executor.schedule(new Task("Task-1"), delay, TimeUnit.MILLISECONDS);
		
		System.out.println("Task is done : " + result.isDone());
		
		if(result.isDone() == false) 
		{
			System.out.println("====Cancelling the task====");

			result.cancel(false);
		}
		
		System.out.println("Task is cancelled : " + result.isCancelled());
		
		System.out.println("Task is done : " + result.isDone());
		
		executor.shutdown();
	}
}

class Task implements Callable<String> 
{
	private final String name;

	public Task(String name) {
		this.name = name;
	}

	@Override
	public String call() throws Exception {
		System.out.println("Task [" + name + "] executed on : " + LocalDateTime.now().toString());
		return "Task [" + name + "] is SUCCESS !!";
	}
}

Program output.

Task scheduled at : 2019-05-23T16:23:52.001

Task is done : false

====Cancelling the task====

Task is cancelled : true

Task is done : true

Clearly, after the task is cancelled the done status of task is also true.

Drop me your questions in comments regarding how to cancel a task submitted to executor in Java.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java Concurrency Tutorial

  • Java Concurrency – Introduction
  • Concurrency Evolution
  • Thread Safety
  • Concurrency vs. Parallelism
  • Compare and Swap [CAS]
  • synchronized keyword
  • Object vs. Class Level Locking
  • Runnable vs. Thread
  • wait(), notify() and notifyAll()
  • Yield() vs. Join()
  • Sleep() vs. Wait()
  • Lock vs. Monitor
  • Callable + Future
  • UncaughtExceptionHandler
  • Throttling Task Submission
  • Executor Best Practices
  • Inter-thread Communication
  • Write and Resolve Deadlock

Java Concurrency Utilities

  • AtomicInteger
  • Lock
  • ThreadFactory
  • ThreadLocal
  • ExecutorService
  • ThreadPoolExecutor
  • FixedSizeThreadPoolExecutor
  • ScheduledThreadPoolExecutor
  • Semaphore
  • Binary Semaphore
  • BlockingQueue
  • DelayQueue
  • ConcurrentLinkedDeque
  • CountDownLatch
  • ForkJoinPool

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)