I have a ThreadPool in my android application where I run a bunch of threads in different situation in it.
public class ThreadPoolExecuter {
private final ExecutorService mExecuter;
private static final int nThreads = 5;
private ThreadPoolExecuter() {
this.mExecuter = Executors.newFixedThreadPool(nThreads);
}
Java ThreadPool have no default to cancel thread. One solution that I thought about was keeping a key-value pairs of Future when I submit runnable.
public void add(Runnable runnable) {
Future<?> future = this.mExecuter.submit(runnable);
// Add future to my key-value pairs
if(Constant.DEBUG) Log.d(TAG, "Task submitted.");
}
And then have a cancel function:
public boolean cancel(KEY) {
Future<?> future = map.get(KEY)
return future.cancel(mayInterruptIfRunning);
}
Let's say a HashMap. The value is the Future, what about key? 1)What is your suggestion?
Map<Key, Future<?>> map = new HashMap()<key, Future<?>>;
About the key I thought about passing an id for every runnable as follows:
2)what do you think about this solution?
But I would mention that in my runnable class sometimes I faced with InterruptedException. Is there any way to avoid it?
class Runner implements Runnable {
private int id;
public Runner(int id) {
this.id = id;
}
@Override
public void run() {
System.out.println("Starting " + id);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Crashed on:" + Thread.currentThread().getId());
}
System.out.println("ending " + id);
}
}
3 ) At the end I want to add it is important for me to know any better solution in your point of view to develop a cancel function in java ThreadPool?
Notice that I don't look for a replacement for my ThreadPool such as AsyncTask in Android which has default cancellation.