Issue in abstracting common code using function interface

后端 未结 1 422
难免孤独
难免孤独 2021-01-25 06:04

here I have implemented two following functions like below:

  Output1 computeFirst(Input1 input) {
        String lockName = input.getId();
        LockItem lock         


        
1条回答
  •  一向
    一向 (楼主)
    2021-01-25 06:35

    Runnable would not work as there is an output as well.

    public interface Identifiable{
        String getId();
    }
    
    public static  R executeWithLock(T input, Function func) {
        String lockName = input.getId();
        LockItem lockItem = acquireLock(lockName);
        try{
            return func.apply(input);
        } catch(Exception e){
            log.error(e);
            return null;
        } finally {
            releaseLock(lockItem);
        }
    }
    

    call like

    Output1 output = executeWithLock(input1, 
        (input) -> {return /*compute output as in critical section*/ null;});
    

    0 讨论(0)
提交回复
热议问题