1

我最近开始在我的一个项目中使用 Java AsynchronousFileChannel,我想尽可能快地写入文件。当我来测试我的项目时,我意识到也许读写操作对我来说并不是真正的异步!我制作了一个非常简单的测试程序,通过将字节写入 2 个文件(每个磁盘一个)来查看写入和读取方法是否阻塞。

ByteBuffer bufferc=ByteBuffer.allocate(75000000);//~75MB
ByteBuffer bufferd=ByteBuffer.allocate(75000000);
for (int i=0; i<75000000; i++)
{   bufferc.put((byte)1);   bufferd.put((byte)1); }

bufferc.flip(); bufferd.flip();

ExecutorService executor = Executors.newFixedThreadPool(10);
AsynchronousFileChannel channelc =AsynchronousFileChannel.open(Paths.get("C:\\ppp"), getReadWriteOptions(),executor, new FileAttribute<?>[0]);
AsynchronousFileChannel channeld =AsynchronousFileChannel.open(Paths.get("D:\\ppp"), getReadWriteOptions(), executor, new FileAttribute<?>[0]);

long  start = System.currentTimeMillis();   
System.out.println("start");
Future futurec=channelc.write(bufferc, 0);
System.out.println(futurec.isDone());
Future futured=channeld.write(bufferd, 0);
System.out.println(futured.isDone());
long elapsedTimec = System.currentTimeMillis()- start; 

channelc.close();
channeld.close();
System.out.println("time="+elapsedTimec);

所以,我将两个缓冲区写入两个不同的文件。因为每个缓冲区大约 75 MB,我想每个缓冲区不能立即写入我的磁盘,所以我希望我的输出类似于

false false time= 

这对我来说意味着写操作被“赋予”给 executorService,并且程序继续运行。在这个程序的多次运行中,这确实发生在我身上,但并非总是如此。我的意思是,我得到像这样的输出

start true true time=2621

或者

start false true time=3039

或者如果我很幸运

start false false time=235

时代真的不同,我什至不明白为什么我会得到前两个输出!我希望有人向我解释影响此输出的因素,和/或我将如何仅获得上述输出中的第三个!

4

0 回答 0