为什么更改初始化RandomAccessFile对象的方式会改变FileChannel的性能?

时间:2012-11-09 04:02:02

标签: java performance filechannel randomaccessfile

我正在调查重写一些代码的可能性,这些代码将磁盘上的瓶颈写入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)等同。

1 个答案:

答案 0 :(得分:3)

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