Improve segmented journal actor metrics
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / index / SparseJournalIndex.java
1 /*
2  * Copyright 2018-2022 Open Networking Foundation and others.  All rights reserved.
3  * Copyright (c) 2024 PANTHEON.tech, s.r.o.
4  *
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
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17 package io.atomix.storage.journal.index;
18
19 import java.util.TreeMap;
20
21 /**
22  * A {@link JournalIndex} maintaining target density.
23  */
24 public final class SparseJournalIndex implements JournalIndex {
25     private static final int MIN_DENSITY = 1000;
26
27     private final int density;
28     private final TreeMap<Long, Integer> positions = new TreeMap<>();
29
30     public SparseJournalIndex() {
31         density = MIN_DENSITY;
32     }
33
34     public SparseJournalIndex(final double density) {
35         this.density = (int) Math.ceil(MIN_DENSITY / (density * MIN_DENSITY));
36     }
37
38     @Override
39     public void index(final long index, final int position) {
40         if (index % density == 0) {
41             positions.put(index, position);
42         }
43     }
44
45     @Override
46     public Position lookup(final long index) {
47         return Position.ofNullable(positions.floorEntry(index));
48     }
49
50     @Override
51     public Position truncate(final long index) {
52         positions.tailMap(index, false).clear();
53         return Position.ofNullable(positions.lastEntry());
54     }
55 }