CompletionService和ObjectPool

时间:2013-02-23 22:54:58

标签: java multithreading threadpool pool future

//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();
 } 

在其中一个工作程序失败后,从帮助程序线程中取消一个thred。 然后,completionService.take()。get()给出CancellationException,因为它已被取消。

因此,myRunnableObj2对象没有返回到池,因为get()在取消时抛出异常。怎么办呢。 ?

0 个答案:

没有答案