android - What is the best way to stop running tasks in threadpoolexecutor? -
i implementing java threadpoolexecutor in android. required stop , remove running tasks pool.
i have implemented using submit(runnable) , future.cancel() methods.
the code submitting tasks 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 submit() passed method below. code cancelling tasks 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 cancelled."); } }
problem : tasks not cancelled. please let me know wrong. appreciated.
please see documentation regarding future task. understand is, if execution started, cannot cancel it. can effect of cancelling interrupt thread running future task
mayinterruptifrunning - true
inside runnable, @ different places, need check whether thread interrupted , return if interrupted , way can cancel it.
thread.isinterrupted()
sample :
private runnable executorrunnable = new runnable() { @override public void run() { // before coming run method only, cancel method has // direct grip. if cancelled, avoid calling run // method. // operation... // checking thread interruption if (thread.currentthread().isinterrupted()) { // means have called cancel true. either raise // exception or simple return. } // operation... // again checking thread interruption if (thread.currentthread().isinterrupted()) { // means have called cancel true. either raise // exception or simple return. } // need check interruption status @ various // points } };
Comments
Post a Comment