Optimize FileChannelJournalSegmentWriter.truncate() 65/110565/2
authorRobert Varga <robert.varga@pantheon.tech>
Sat, 9 Mar 2024 13:09:45 +0000 (14:09 +0100)
committerRobert Varga <nite@hq.sk>
Mon, 11 Mar 2024 12:51:11 +0000 (12:51 +0000)
FileChannelJournalSegmentWriter.truncate() is inefficient in that it
zeroes-out its memory buffer and then writes it completely out.

This patch aligns it with what MappedJournalSegmentWriter does, which is
just zeroing out the entry header -- reducing both IO and CPU overheads.

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

index b43aa3d443fbe08eaccc0c851bd33418c832a855..025e1a841b1fe7bd3ee211b0adbc73f43b3801bd 100644 (file)
@@ -42,6 +42,8 @@ import java.util.zip.Checksum;
  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
  */
 class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
+  private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[Integer.BYTES + Integer.BYTES]);
+
   private final FileChannel channel;
   private final JournalSegment<E> segment;
   private final int maxEntrySize;
@@ -256,15 +258,8 @@ class FileChannelJournalSegmentWriter<E> implements JournalWriter<E> {
         reset(index);
       }
 
-      // 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());
+      // Zero the entry header at current channel position.
+      channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), channel.position());
     } catch (IOException e) {
       throw new StorageException(e);
     }