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 static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
20 import java.io.IOException;
21 import java.nio.ByteBuffer;
22 import java.nio.MappedByteBuffer;
23 import java.nio.channels.FileChannel;
26 * A {@link StorageLevel#DISK} {@link FileWriter}.
28 final class DiskFileWriter extends FileWriter {
29 private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[HEADER_BYTES]);
31 private final DiskFileReader reader;
32 private final ByteBuffer buffer;
34 DiskFileWriter(final JournalSegmentFile file, final FileChannel channel, final int maxEntrySize) {
35 super(file, channel, maxEntrySize);
36 buffer = DiskFileReader.allocateBuffer(file.maxSize(), maxEntrySize);
37 reader = new DiskFileReader(file, channel, buffer);
41 DiskFileReader reader() {
46 MappedByteBuffer buffer() {
51 MappedFileWriter toMapped() {
53 return new MappedFileWriter(file, channel, maxEntrySize);
57 DiskFileWriter toDisk() {
62 void writeEmptyHeader(final int position) {
64 channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), position);
65 } catch (IOException e) {
66 throw new StorageException(e);
71 ByteBuffer startWrite(final int position, final int size) {
72 return buffer.clear().slice(0, size);
76 void commitWrite(final int position, final ByteBuffer entry) {
78 channel.write(entry, position);
79 } catch (IOException e) {
80 throw new StorageException(e);
86 if (channel.isOpen()) {
89 } catch (IOException e) {
90 throw new StorageException(e);