Java7 新特性之自动关闭资源

        话不多说,直接上代码:

public static class TimerContext implements AutoCloseable {

    final Timer.Context ctx;

    TimerContext(Timer.Context ctx) {
        this.ctx = ctx;
    }

    @Override
    public void close() {
        this.ctx.close();
    }
}

       上面这段代码具体是做什么的,大家不用记,只需要看到该类实现类 AutoCloseable 接口,并且重写类 close 方法。顾名思义,就是实现自动关闭的。

        接下来再看下面一段代码:

if (action.equals("fun")) {
    try (MetricsService.TimerContext ignored = MetricsService.timer(MetricsService.TimerType.WS_REQUEST_FUN)) {
        this.marketFunService.fun(event, jsonObject.getJSONObject("parameters"), session);
    }
}

        这里用到了我们此篇文章要说的主题:try (...) {...} 

        什么意思那,就是:try (...) 里的东西,会等待 {...} 里的语句执行完以后,自动进行关闭,仅此而已,但却相当方便!

猜你喜欢

转载自blog.csdn.net/qq_34074510/article/details/81127886