AsynchronousFileChannel写入失败

时间:2014-11-23 19:50:48

标签: java netty nio2

我正在尝试使用AsynchronousFileChannel.write将文件写入文件:

    ...
    Path filePath = Paths.get(path + "/" + System.currentTimeMillis()
            + ".jpeg");
    try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(filePath,
            StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);) {
        CompletionHandler<Integer, Object> handler = new CompletionHandler<Integer, Object>() {

            @Override
            public void failed(Throwable exc, Object attachment) {
                logger.error("Write failed: ", exc);
            }

            @Override
            public void completed(Integer result, Object attachment) {
                ...
            }
        };

        ByteBuf buffer = Unpooled.buffer(request.getImage().length);
        buffer.writeBytes(request.getImage());
        channel.write(buffer.nioBuffer(), 0, null, handler);
    } catch (IOException e) {
        logger.error("Failed to open file: ", e);
        throw new RuntimeException(e);
    }

....

我经常收到以下例外:

java.nio.channels.AsynchronousCloseException: null
    at sun.nio.ch.SimpleAsynchronousFileChannelImpl$3.run(SimpleAsynchronousFileChannelImpl.java:380) ~[na:1.8.0_25]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_25]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_25]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_25]

我使用Oracle JDK 8u25在Linux上运行此代码。在Windows上,这种情况很少发生。我还注意到,当我在调试模式下运行代码时,逐步执行每行代码,很少发生。

当我不使用CompletionHandler时,而是使用:

    Future<Integer> writeFuture = channel.write(buffer.nioBuffer(), 0);
    Integer integer = writeFuture.get();

我没有得到例外。

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:1)

我认为这是因为当你离开try {...}块时你会自动关闭Channel,而你正在做的写是异步的,这意味着如果写得不够快,你会尝试写到一个封闭的渠道。

相关问题