What is the best way to stop running tasks in threadpoolexecutor?
android, threadpoolexecutor
Solution
Please see the documentation regarding the Future task. From that what I understand is, if the execution started, we cannot cancel it. Then what we can do to get the effect of cancelling is to interrupt the thread which is running the Future task
mayInterruptIfRunning - true
Inside your runnable, at different places, you need to check whether the thread is Interrupted and return if interrupted and by that way only we can cancel it.
Thread.isInterrupted()
Sample :
private Runnable ExecutorRunnable = new Runnable() {
@Override
public void run() {
// Before coming to this run method only, the cancel method has
// direct grip. like if cancelled, it will avoid calling the run
// method.
// Do some Operation...
// Checking for thread interruption
if (Thread.currentThread().isInterrupted()) {
// Means you have called Cancel with true. So either raise an
// exception or simple return.
}
// Do some Operation...
// Again Checking for thread interruption
if (Thread.currentThread().isInterrupted()) {
// Means you have called Cancel with true. So either raise an
// exception or simple return.
}
// Similarly you need to check for interruption status at various
// points
}
};
Problem
I am implementing Java ThreadPoolExecutor in Android. I am required to stop and remove running tasks from my pool. I have implemented this by using submit(Runnable) and Future.cancel() methods. The code for submitting tasks is below: ``` public Future<?> submitTask(Runnable runnableTask) throws CustomException { if (runnableTask == null) { throw new CustomException("Null RunnableTask."); } Future<?> future = threadPoolExecutor.submit(runnableTask); return future; } ``` The Future returned by submit() is passed to method below. The code for cancelling tasks is below: ``` public void cancelRunningTask(Future<?> future) throws CustomException { if (future == null) { throw new CustomException("Null Future<?>."); } if (!(future.isDone() || future.isCancelled())) { if (future.cancel(true)) MyLogger.d(this, "Running task cancelled."); else MyLogger.d(this, "Running task cannot be cancelled."); } } ``` Problem : The tasks are not actually cancelled. Please let me know where I am wrong. Any help would be appreciated.