Search code examples
javaaio

What efficiency is the AsynchronousFileChannel on windows os?


I'm learning about the Java NIO.2 API these days, I did a test to compare the efficiency between AIO and the Standard IO,The test is to write a 2000M file.Here is the code.

The standard way:

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");

the result is taking time:10392ms

The AIO way:

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");

the result is taking time:15652ms

I think,in the second case,the program submits 2000 writing requests to the OS. the OS will run the IO operation with it's own thread pool. in other words,thread pool size IO operations will execute concurrently. it shoud be faster in the second case. But the fact is exactly the opposite,Why?


Solution

  • Before the program submit writing requests,the file is locked until the end of the writing operation.In other word,only one operation is allowed by the AsynchronousFileChannel at the same time.So multi-thread is invalid.