0
//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. ?

fortm
  • 4,066
  • 5
  • 49
  • 79
  • As a temporary solution, I will look to set future.cancel(false) so that I avoid messing up running tasks and reduce comlpexity.. – fortm Feb 24 '13 at 20:02
  • Would you please provide more information? I can not understand your question from the incomplete code snippet. – ericson Feb 25 '13 at 01:51
  • Sure, I will explain the code. There is worker MyRunnable. This is submitted to CompletionService from another Thread [ code snippet in between ]. So, whenever a worker thread finish either with sucess / with INterruptException, I need to release that object from pool as a cleanup step. so, I have a third thread for monitoring completionService and releasing resource + getting their return status. – fortm Feb 25 '13 at 13:00
  • When a status is received as false, rest of threads including those running are cancelled and this sends InterruptedException to them. I catch that Exception in those worker threads and return. But, completionService.take().get() then starts throwing CancellationException and I don't have reference to object that was running and as a result, I am not able to return it back to pool. – fortm Feb 25 '13 at 13:00
  • I am thinking of passing Pool to each Worker Thread and in finally block of Worker Thread, I can then release it without loosing reference. – fortm Feb 25 '13 at 13:02

0 Answers0