Skip to content

Instantly share code, notes, and snippets.

@sassit
Created January 12, 2013 11:00
Show Gist options
  • Select an option

  • Save sassit/4517191 to your computer and use it in GitHub Desktop.

Select an option

Save sassit/4517191 to your computer and use it in GitHub Desktop.
The attempt to write to dedicated bytebuffers per thread.
abstract class RandomAccessFileWriterTemplate implements Writer<ByteBuffer[]> {
private final File file;
public RandomAccessFileWriterTemplate(File file) {
this.file = file;
}
public void write() {
RandomAccessFile randomAccessFile;
FileChannel channel = null;
try {
randomAccessFile = new RandomAccessFile(file, "rw");
channel = randomAccessFile.getChannel();
ByteBuffer[] buffers = new ByteBuffer[10];
for (int i = 0; i < buffers.length; i++) {
buffers[i] = ByteBuffer.allocateDirect(1 * MB);
}
write(buffers);
long position = 0;
for (int i = 0; i < buffers.length; i++) {
buffers[i].flip();
channel.write(buffers[i], position);
position += buffers[i].position();
}
channel.truncate(position);
} catch (Exception e) {
throw new ParserException("Could not write the file:", e);
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
throw new ParserException("Could not close file.", e);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment