我试图使用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();我不明白例外。
是什么导致了这一切?
发布于 2014-11-24 05:20:32
我认为这是因为当您离开try {.}块时自动关闭通道,而您正在执行的写操作是异步的,这意味着如果您的写入速度不快,那么您将尝试写入关闭的通道。
https://stackoverflow.com/questions/27093541
复制相似问题