【Java记录】try-with-resources的一个坑

##【Java记录】try-with-resources的一个坑

今天处理 AsynchronousFileChannel 时候的一个问题,代码如下:

public static void main(String[] args) throws Exception {

    String filePath = "/home/xe/git/osc/JavaNote/Lang/data/Test.java";
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Set<OpenOption> openOptions = new HashSet<>(Arrays.asList(new StandardOpenOption[]{StandardOpenOption.READ}));

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(Paths.get(filePath), openOptions, executorService)) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        asynchronousFileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                System.out.println("completed,result = " + result);
                executorService.shutdown();
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                System.out.println("failed");
                exc.printStackTrace();
                executorService.shutdown();
            }
        });
    } catch (Exception e) {
    }
}

一直提示:

java.nio.channels.AsynchronousCloseException

一直找不到问题的原因,因为我并没有显式的去关闭 AsynchronousFileChannel,后来才发现,是被 try-with-resources 特性给关闭了,悲伤的故事。

所以,在异步调用中, 还是谨慎的处理通告的关闭操作比较好。

转载于:https://my.oschina.net/xesam/blog/413018

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值