2 * Copyright (c) 2024 PANTHEON.tech, s.r.o. 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.netty.util.internal.PlatformDependent;
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.MappedByteBuffer;
22 import org.eclipse.jdt.annotation.NonNull;
25 * A {@link StorageLevel#MAPPED} {@link FileWriter}.
27 final class MappedFileWriter extends FileWriter {
28 private final @NonNull MappedByteBuffer mappedBuffer;
29 private final MappedFileReader reader;
30 private final ByteBuffer buffer;
32 MappedFileWriter(final JournalSegmentFile file, final int maxEntrySize) {
33 super(file, maxEntrySize);
36 mappedBuffer = file.map();
37 } catch (IOException e) {
38 throw new StorageException(e);
40 buffer = mappedBuffer.slice();
41 reader = new MappedFileReader(file, mappedBuffer);
45 MappedFileReader reader() {
50 MappedByteBuffer buffer() {
55 MappedFileWriter toMapped() {
60 DiskFileWriter toDisk() {
62 return new DiskFileWriter(file, maxEntrySize);
66 void writeEmptyHeader(final int position) {
67 // Note: we issue a single putLong() instead of two putInt()s.
68 buffer.putLong(position, 0L);
72 ByteBuffer startWrite(final int position, final int size) {
73 return buffer.slice(position, size);
77 void commitWrite(final int position, final ByteBuffer entry) {
78 // No-op, buffer is write-through
89 PlatformDependent.freeDirectBuffer(mappedBuffer);