【问题标题】:What efficiency is the AsynchronousFileChannel on windows os?windows os上的AsynchronousFileChannel效率如何?
【发布时间】:2018-03-13 08:31:09
【问题描述】:

这几天在学习Java NIO.2 API,做了一个测试,比较AIO和Standard IO的效率,测试是写一个2000M的文件,代码如下。

标准方式:

FileOutputStream output = new FileOutputStream(tmp);
byte[] byteArr = new byte[1024 * 1024];
for (int i = 0; i < 1024 * 1024; i++) {
    byteArr[i] = 1;
}
long start = System.currentTimeMillis();
while (length -- > 0) {
    output.write(byteArr);
}
System.out.println("taking time:" + (System.currentTimeMillis() - start) + "ms");

结果是taking time:10392ms

AIO 方式:

AsynchronousFileChannel afc   = AsynchronousFileChannel.open(path, WRITE, CREATE);
List<Future<Integer>> results = new ArrayList<>();
ByteBuffer buf = ByteBuffer.allocate(1024 * 1024);
buf.clear();
for (int j = 0; j < 1024 * 1024; j++) {
    buf.put((byte) 1);
}
buf.flip();
buf.mark();
long start = System.currentTimeMillis();
for (int i = 0; i < 2000; i ++) {
    buf.reset();
    results.add(afc.write(buf, i * 1024 *1024));
}
for(Future<Integer> future : results) {
    future.get();
}
System.out.println("taking time:" + (System.currentTimeMillis() - start) + "ms");

结果是taking time:15652ms

我认为,在第二种情况下,程序向操作系统提交了 2000 个写入请求。操作系统将使用自己的线程池运行 IO 操作。换句话说,thread pool size IO 操作将并发执行。在第二种情况下应该更快。但事实恰恰相反,为什么呢?

【问题讨论】:

    标签: java aio


    【解决方案1】:

    在程序提交写请求之前,文件被锁定直到写操作结束。也就是说AsynchronousFileChannel同时只允许一个操作。所以多线程是无效的。

    【讨论】:

    • 文件未锁定。 写操作可能会被阻塞,或者线程池可能会强制对同一个文件的操作按顺序执行,或者操作系统可能会将它们按顺序排列:磁盘控制器肯定会将它们按顺序排列。
    猜你喜欢
    • 2016-01-16
    • 2014-07-18
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多