2 * Copyright 2018-present Open Networking Foundation
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.MappedByteBuffer;
21 import java.nio.channels.FileChannel;
24 * Mappable log segment writer.
26 final class MappableJournalSegmentWriter<E> implements JournalWriter<E> {
27 private final FileChannel channel;
28 private final JournalSegment<E> segment;
29 private JournalSegmentWriter<E> writer;
31 MappableJournalSegmentWriter(
33 JournalSegment<E> segment,
36 JournalSerdes namespace) {
37 this.channel = channel;
38 this.segment = segment;
39 this.writer = new FileChannelJournalSegmentWriter<>(channel, segment, maxEntrySize, index, namespace);
43 * Maps the segment writer into memory, returning the mapped buffer.
45 * @return the buffer that was mapped into memory
47 MappedByteBuffer map() {
48 final var mapped = writer.toMapped();
50 return mapped.buffer();
54 * Unmaps the mapped buffer.
57 writer = writer.toFileChannel();
60 MappedByteBuffer buffer() {
61 return writer.buffer();
65 * Returns the writer's first index.
67 * @return the writer's first index
69 public long firstIndex() {
70 return segment.index();
74 * Returns the size of the segment.
76 * @return the size of the segment
80 return (int) channel.size();
81 } catch (IOException e) {
82 throw new StorageException(e);
87 public long getLastIndex() {
88 return writer.getLastIndex();
92 public Indexed<E> getLastEntry() {
93 return writer.getLastEntry();
97 public long getNextIndex() {
98 return writer.getNextIndex();
102 public <T extends E> Indexed<T> append(T entry) {
103 return writer.append(entry);
107 public void append(Indexed<E> entry) {
108 writer.append(entry);
112 public void commit(long index) {
113 writer.commit(index);
117 public void reset(long index) {
122 public void truncate(long index) {
123 writer.truncate(index);
127 public void flush() {
132 public void close() {
136 } catch (IOException e) {
137 throw new StorageException(e);