0

我正在研究将一些在磁盘上出现瓶颈的代码重写到 java 中的可能性。javadoc 没有说明为什么下面的前两个代码循环与后两个循环的执行方式如此不同:

public void testFileChannel() throws IOException {
    RandomAccessFile raf = new RandomAccessFile(new File("/tmp/t5"),"rw");
    FileChannel c = raf.getChannel();
    c.force(true);
    ByteBuffer b = ByteBuffer.allocateDirect(64*1024);
    long s = System.currentTimeMillis();
    for(int i=0;i<size;i++){            
        b.clear();
        b.put(data.getBytes());
        b.flip();
        c.write(b);
    }
    long e=System.currentTimeMillis();
    raf.close();
    System.out.println("FileChannel rw force=true "+(e-s));

    raf = new RandomAccessFile(new File("/tmp/t5"),"rw");
    raf.seek(0);
    c = raf.getChannel();
    c.force(false);
    b = ByteBuffer.allocateDirect(64*1024);
    s = System.currentTimeMillis();
    for(int i=0;i<size;i++){            
        b.clear();
        b.put(data.getBytes());
        b.flip();
        c.write(b);
    }
    e=System.currentTimeMillis();
    raf.close();
    System.out.println("FileChannel rw force=false "+(e-s));

    raf = new RandomAccessFile(new File("/tmp/t5"),"rwd");
    raf.seek(0);
    c = raf.getChannel();
    c.force(true);
    b = ByteBuffer.allocateDirect(64*1024);
    s = System.currentTimeMillis();
    for(int i=0;i<size;i++){            
        b.clear();
        b.put(data.getBytes());
        b.flip();
        c.write(b);
    }
    e=System.currentTimeMillis();
    raf.close();
    System.out.println("FileChannel rwd force=true "+(e-s));


    raf = new RandomAccessFile(new File("/tmp/t5"),"rwd");
    raf.seek(0);
    c = raf.getChannel();
    c.force(true);
    b = ByteBuffer.allocateDirect(64*1024);
    s = System.currentTimeMillis();
    for(int i=0;i<size;i++){            
        b.clear();
        b.put(data.getBytes());
        b.flip();
        c.write(b);
    }
    e=System.currentTimeMillis();
    raf.close();
    System.out.println("FileChannel rws force=true "+(e-s));
}

public static final int size = 10000;
public static final String data = "123456789012345678901234567890";

运行此代码会产生如下内容:

FileChannel rw force=true 273
FileChannel rw force=false 40 // Forcing writes to disk is slower than above.
FileChannel rwd force=true 4179 // Why is this slower?!
FileChannel rwd force=true 4212

如您所见,这会使c.force(true)事情变慢一点。为什么在使用RandomAccessFile“rwd”模式时事情会更慢。不应该“rwd”并且c.force(true)是等效的。

4

1 回答 1

3

根据 JavaDoc,c.force(whatever) 只是在该方法返回之前将内容推送到磁盘,而使用“rwd”打开时为每个 I/O 执行此操作。

于 2012-11-09T04:11:20.167 回答