2 * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
3 * Copyright (c) 2024 PANTHEON.tech, s.r.o.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package io.atomix.storage.journal.index;
19 import java.util.TreeMap;
22 * A {@link JournalIndex} maintaining target density.
24 public final class SparseJournalIndex implements JournalIndex {
25 private static final int MIN_DENSITY = 1000;
27 private final int density;
28 private final TreeMap<Long, Integer> positions = new TreeMap<>();
30 public SparseJournalIndex() {
31 density = MIN_DENSITY;
34 public SparseJournalIndex(final double density) {
35 this.density = (int) Math.ceil(MIN_DENSITY / (density * MIN_DENSITY));
39 public void index(final long index, final int position) {
40 if (index % density == 0) {
41 positions.put(index, position);
46 public Position lookup(final long index) {
47 return Position.ofNullable(positions.floorEntry(index));
51 public Position truncate(final long index) {
52 positions.tailMap(index, false).clear();
53 return Position.ofNullable(positions.lastEntry());