//Worker Thread
class MyRunnable implements Runnable {
private String status;
public void getStatus() {
return status;
}
public void run() {
try {
if(Thread.interrupted()) throw new InterruptedException();
}catch(InterruptedException ie) {
status= "FAIL";
return;
}
}
//Thread that submits Workers
MyRunnable myRunnableObj1 = getObjectPool().borrow();
futures.add(completionService.submit(myRunnableObj1,myRunnableObj1));
//A Helper thread to return Objects to pool
new Callable() {
public String call() {
MyRunnable myRunnableObj2 = completionService.take().get();
getObjPool().returnObject(myRunnableObj2):
if(myRunnableObj2.getStatus= "FAIL") {
for(Future future : futures) {
if(!future.isDone())
future.cancel(true);
}
return myRunnableObj2.getStatus();
}
Once a thred is cancelled from the helper thread after one of the workers fail. Then, completionService.take().get() gives CancellationException as it is already cancelled.
AS a result, myRunnableObj2 object is not getting returned to pool as get() is throwing Exception on cancellation. How can this be handled. ?