Function接口中的exception处理
我是Java 8中的Function接口的新手。这个问题与使用函数接口抽象公共代码的问题有关。 从中得到想法我写的如下:
public void act(Input1 input) throws NonRetriableException, InvalidInputException { Function func = item -> { try { activityManager.update(item); return true; } catch (InterruptedException | JSONException e) { throw new NonRetriableException(e); } catch (LockUnavailableException e) { throw new NonRetriableException(e); } }; try { lockManager.executeWithLock(input.getTaskID(), input, func); } catch (LockUnavailableException e) { log.error("{}",e); throw new NonRetriableException(e); } }
和:
public void perform() throws AutoAllocationException { Function func = item -> { try { activityManager.allocateTask(item); return true; } catch (AutoAllocationException ex) { log.error("{}",ex); } return false; }; try { lockManager.executeWithLock(input.getTaskID(), input, func); } catch (LockUnavailableException e) { log.error("{}",e); } }
LockManager中的executeWithLock()如下:
@Override public R executeWithLock(String lockName, T input, Function func) throws LockUnavailableException { LockItem lockItem = acquireLock(lockName); R output = func.apply(input); releaseLock(lockItem); return output; }
现在我的问题是:
在executeWithLock()
函数中我是否必须捕获所有exception,我的意思是我应该从func.apply()
处理exception。 我想知道这个因为, releaseLock
调用我应该总是这样做,不管事件是否发生过。
如果act
抛出exception,则不会在executeWithLock
释放executeWithLock
。 因此, 建议在使用Lock
时使用try-finally语句:
public R executeWithLock(String lockName, T input, Function func) throws LockUnavailableException { LockItem lockItem = acquireLock(lockName); try { R output = func.apply(input); return output; } finally { releaseLock(lockItem); } }
另一点:
因为act
在一个Function
抛出一个NonRetriableException
,它没有声明任何暗示NonRetriableException extends RuntimeException
Exception
会NonRetriableException extends RuntimeException
。 但是下面的try-catch-block只捕获LockUnavailableException
类型的LockUnavailableException
。 不会NonRetriableException
类型NonRetriableException
exception,因此不会处理(记录)。 它们将被传播到act
的调用者,这是executeWithLock
。 这再次显示了第一点的重要性。