【问题标题】:Calllable and exception handling可调用和异常处理
【发布时间】:2013-09-11 19:04:07
【问题描述】:

我正在使用 ThreadPool 执行器,并使用 invokeAll() 方法调用任务。在可调用的 call() 方法中,我写入数据库,但如果我确定线程执行良好并且没有严重终止,我只想写入。

这些解决方案是否有效:

解决方案 1

我认为这不起作用,因为线程可以在数据库写入后被中断,所以它不会返回结果,我猜。

public Result call() throws exception(){

    ...

    if( !Thread.currentThread.isInterrupted() ){
       //Save to the database
    } 

    ...

    return result;
}

解决方案 2

在 get() 方法之后处理写入以确保它正常终止,如果我理解正确,get() 方法会重新抛出执行期间捕获的任何异常

...

for( Future f : futures){

   try {

       Result r = f.get();

       //Do the write with the result i got
   }
   catch( Exception e){
     //Something went wrong
   }

}

提前致谢。

【问题讨论】:

    标签: java android exception threadpool callable


    【解决方案1】:

    在可调用的 call() 方法中,我写入数据库...

    这种情况下,异常处理逻辑需要在call()方法本身;例如

    public Result call() {
        try {
           ...
           if (!Thread.currentThread.isInterrupted()) {
              // Save to the database
              return result;
           } else {
              return // some result that means interrupted.
           }
        catch (Exception ex) {
           return // some result that means failed.
        }
    }
    

    尝试让主线程进行数据库保存似乎没有任何意义。

    【讨论】:

    • @Sthepen 谢谢我认为这解决了问题,在调用方法中处理异常更有意义是。我在想你的例子,即使我写入数据库并且之后发生异常,如果需要,我仍然可以回滚 catch 块中的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    相关资源
    最近更新 更多