Question

Im investigating the possibility of re-writing some code that bottlenecks on disk writes into java. The javadoc does not make clear why the first two code loops below would perform so differently to the second two loops:

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

Running this code produces something like this:

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

As you can see, c.force(true) slows things down a little. Why should things slow down more when using the RandomAccessFile "rwd" mode. Shouldnt "rwd" and c.force(true) be equivalent.

Était-ce utile?

La solution

According to JavaDoc, c.force(whatever) just push the things to the disk before that method returns, while open with "rwd" do that for every I/O.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top