Improve FileChannelJournalSegmentWriter.truncate() 63/110563/3
authorRobert Varga <robert.varga@pantheon.tech>
Sat, 9 Mar 2024 12:30:12 +0000 (13:30 +0100)
committerRobert Varga <nite@hq.sk>
Mon, 11 Mar 2024 12:51:11 +0000 (12:51 +0000)
Reduce the dance around channel position by explicitly passing it down,
thus reducing the number of syscalls we incur.

Also inline FileChannelJournalSegmentWriter.zero() and add a FIXME to
improve our zero-out strategy.

JIRA: CONTROLLER-2095
Change-Id: I885947fef51132a294c900396d902cf5481e2bd8
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
atomix-storage/src/main/java/io/atomix/storage/journal/FileChannelJournalSegmentWriter.java

index 5c7af3fdb4f361ae1355e45fd43b9943db51ae85..b43aa3d443fbe08eaccc0c851bd33418c832a855 100644 (file)
@@ -244,39 +244,32 @@ class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
     // Reset the last entry.
     lastEntry = null;
 
-    try {
-      // Truncate the index.
-      this.index.truncate(index);
+    // Truncate the index.
+    this.index.truncate(index);
 
+    try {
       if (index < segment.index()) {
-        channel.position(JournalSegmentDescriptor.BYTES);
-        channel.write(zero());
+        // Reset the writer to the first entry.
         channel.position(JournalSegmentDescriptor.BYTES);
       } else {
         // Reset the writer to the given index.
         reset(index);
+      }
 
-        // Zero entries after the given index.
-        long position = channel.position();
-        channel.write(zero());
-        channel.position(position);
+      // Zero entries at the current position.
+      // FIXME: This is quite inefficient, we essentially want to zero-out part of the file, but it is not quite clear
+      //        how much: this overwrites at least two entries. I believe we should be able to get by with wiping the
+      //        header of the current entry.
+      memory.clear();
+      for (int i = 0; i < memory.limit(); i++) {
+        memory.put(i, (byte) 0);
       }
+      channel.write(memory, channel.position());
     } catch (IOException e) {
       throw new StorageException(e);
     }
   }
 
-  /**
-   * Returns a zeroed out byte buffer.
-   */
-  private ByteBuffer zero() {
-    memory.clear();
-    for (int i = 0; i < memory.limit(); i++) {
-      memory.put(i, (byte) 0);
-    }
-    return memory;
-  }
-
   @Override
   public void flush() {
     try {