环绕执行模式【其他模式】

环绕执行模式

@Slf4j
public class ExecuteAround {

    /**
     * Execute Aorund【环绕执行】:能够将资源获取和释放封装在一个横切点上统一管理
     */
    @Test
    public void all() {
        final ReentrantLock lock = new ReentrantLock();
        AroundExecutor.lockAction(lock, () -> {
            log.info("do business");
        });
    }
}

@Slf4j
class AroundExecutor {
    static void lockAction(Lock lock, Action action) {
        try {
            lock.lock();
            log.info("lock held by {}", Thread.currentThread().getName());
            action.execute();
        } finally {
            lock.unlock();
            log.info("lock release by {}", Thread.currentThread().getName());
        }
    }
}

interface Action {
    void execute();
}

posted on 2019-01-02 20:23  竺旭东  阅读(119)  评论(0编辑  收藏  举报

导航