I need to manage many background threads that do something with some objects as key but only one thread can work with same object at the same time, For example while thread A
is working on object A
, if thread B
called for working with object A
, thread A
should be canceled before thread B
can run.
Here is my code, but when I run, The first thread doesn't stop and continues with second one:
private static ExecutorService mExecutor = Executors.newCachedThreadPool();
private static ConcurrentMap<Object, Future> mRunningTasks = new ConcurrentHashMap<>();
public static void run(final Runnable runnable, final Object key) {
Future<?> future = mRunningTasks.get(key);
if (future != null) {
future.cancel(true);
}
future = new FutureTask<>(new Runnable() {
@Override
public void run() {
//How to handle InterruptedException here ?
//while there's no potential to throw an InterruptedException
runnable.run();
mRunningTasks.remove(key);
}
}, null);
mRunningTasks.put(key, future);
mExecutor.execute((FutureTask) future);
}
What am I missing here ?
Thanks in advance.
PS:
I need a behavior like Picasso
API when cancels requests using an ImageView
as a key object.