2 * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.storage.journal;
18 import io.atomix.storage.journal.index.JournalIndex;
19 import java.io.IOException;
20 import java.nio.BufferUnderflowException;
21 import java.nio.ByteBuffer;
22 import java.nio.channels.FileChannel;
23 import java.util.zip.CRC32;
28 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
30 final class FileChannelJournalSegmentReader<E> extends JournalSegmentReader<E> {
31 private final FileChannel channel;
32 private final ByteBuffer memory;
33 private long currentPosition;
35 FileChannelJournalSegmentReader(
37 JournalSegment<E> segment,
40 JournalSerdes namespace) {
41 super(segment, maxEntrySize, index, namespace);
42 this.channel = channel;
43 this.memory = ByteBuffer.allocate((maxEntrySize + JournalSegmentWriter.ENTRY_HEADER_BYTES) * 2);
48 void setPosition(int position) {
49 currentPosition = position;
50 memory.clear().flip();
54 Indexed<E> readEntry(final long index) {
56 // Read more bytes from the segment if necessary.
57 if (memory.remaining() < maxEntrySize) {
58 long position = currentPosition + memory.position();
59 channel.read(memory.clear(), position);
60 currentPosition = position;
64 // Mark the buffer so it can be reset if necessary.
68 // Read the length of the entry.
69 final int length = memory.getInt();
71 // If the buffer length is zero then return.
72 if (length <= 0 || length > maxEntrySize) {
73 memory.reset().limit(memory.position());
77 // Read the checksum of the entry.
78 long checksum = memory.getInt() & 0xFFFFFFFFL;
80 // Compute the checksum for the entry bytes.
81 final CRC32 crc32 = new CRC32();
82 crc32.update(memory.array(), memory.position(), length);
84 // If the stored checksum equals the computed checksum, return the entry.
85 if (checksum == crc32.getValue()) {
86 int limit = memory.limit();
87 memory.limit(memory.position() + length);
88 E entry = namespace.deserialize(memory);
90 return new Indexed<>(index, entry, length);
92 memory.reset().limit(memory.position());
95 } catch (BufferUnderflowException e) {
96 memory.reset().limit(memory.position());
99 } catch (IOException e) {
100 throw new StorageException(e);