Debian Codegraph @

src/main/org/h2/util/MemoryEstimator.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.util;
7
8 import static org.h2.engine.Constants.MEMORY_POINTER;
9
10 import java.util.concurrent.atomic.AtomicLong;
11
12 import org.h2.mvstore.type.DataType;
13
14 /**
15 * Class MemoryEstimator.
16 *
17 * Calculation of the amount of memory occupied by keys, values and pages of the MVTable
18 * may become expensive operation for complex data types like Row.
19 * On the other hand, result of the calculation is used by page cache to limit it's size
20 * and determine when eviction is needed. Another usage is to trigger auto commit,
21 * based on amount of unsaved changes. In both cases reasonable (lets say ~30%) approximation
22 * would be good enough and will do the job.
23 * This class replaces exact calculation with an estimate based on
24 * a sliding window average of last 256 values.
25 * If estimation gets close to the exact value, then next N calculations are skipped
26 * and replaced with the estimate, where N depends on the estimation error.
27 *
28 * @author <a href='mailto:[email protected]'>Andrei Tokar</a>
29 */
30 public final class MemoryEstimator {
31
32 // Structure of statsData long value:
33 // 0 - 7 skip counter (how many more requests will skip calculation and use an estimate instead)
34 // 8 - 23 total number of skips between last 256 calculations
35 // (used for sampling percentage calculation only)
36 // 24 bit is 0 when window is not completely filled yet, 1 once it become full
37 // 25 - 31 unused
38 // 32 - 63 sliding window sum of estimated values
39
40 private static final int SKIP_SUM_SHIFT = 8;
41 private static final int COUNTER_MASK = (1 << SKIP_SUM_SHIFT) - 1;
42 private static final int SKIP_SUM_MASK = 0xFFFF;
43 private static final int INIT_BIT_SHIFT = 24;
44 private static final int INIT_BIT = 1 << INIT_BIT_SHIFT;
45 private static final int WINDOW_SHIFT = 8;
46 private static final int MAGNITUDE_LIMIT = WINDOW_SHIFT - 1;
47 private static final int WINDOW_SIZE = 1 << WINDOW_SHIFT;
48 private static final int WINDOW_HALF_SIZE = WINDOW_SIZE >> 1;
49 private static final int SUM_SHIFT = 32;
50
51 private MemoryEstimator() {}
52
53 /**
54 * Estimates memory size of the data based on previous values.
55 * @param stats AtomicLong holding statistical data about the estimated sequence
56 * @param dataType used for calculation of the next sequence value, if necessary
57 * @param data which size is to be calculated as the next sequence value, if necessary
58 * @param <T> type of the data
59 * @return next estimated or calculated value of the sequence
60 */
61 public static <T> int estimateMemory(AtomicLong stats, DataType<T> dataType, T data) {
62 long statsData = stats.get();
63 int counter = getCounter(statsData);
64 int skipSum = getSkipSum(statsData);
65 long initialized = statsData & INIT_BIT;
66 long sum = statsData >>> SUM_SHIFT;
67 int mem = 0;
68 int cnt = 0;
69 if (initialized == 0 || counter-- == 0) {
70 cnt = 1;
71 mem = data == null ? 0 : dataType.getMemory(data);
72 long delta = ((long) mem << WINDOW_SHIFT) - sum;
73 if (initialized == 0) {
74 if (++counter == WINDOW_SIZE) {
75 initialized = INIT_BIT;
76 }
77 sum = (sum * counter + delta + (counter >> 1)) / counter;
78 } else {
79 long absDelta = delta >= 0 ? delta : -delta;
80 int magnitude = calculateMagnitude(sum, absDelta);
81 sum += ((delta >> (MAGNITUDE_LIMIT - magnitude)) + 1) >> 1;
82 counter = ((1 << magnitude) - 1) & COUNTER_MASK;
83
84 delta = (counter << WINDOW_SHIFT) - skipSum;
85 skipSum += (delta + WINDOW_HALF_SIZE) >> WINDOW_SHIFT;
86 }
87 }
88 long updatedStatsData = updateStatsData(stats, statsData, counter, skipSum, initialized, sum, cnt, mem);
89 return getAverage(updatedStatsData);
90 }
91
92 /**
93 * Estimates memory size of the data set based on previous values.
94 * @param stats AtomicLong holding statistical data about the estimated sequence
95 * @param dataType used for calculation of the next sequence value, if necessary
96 * @param storage of the data set, which size is to be calculated
97 * @param count number of data items in the storage
98 * @param <T> type of the data in the storage
99 * @return next estimated or calculated size of the storage
100 */
101 public static <T> int estimateMemory(AtomicLong stats, DataType<T> dataType, T[] storage, int count) {
102 long statsData = stats.get();
103 int counter = getCounter(statsData);
104 int skipSum = getSkipSum(statsData);
105 long initialized = statsData & INIT_BIT;
106 long sum = statsData >>> SUM_SHIFT;
107 int index = 0;
108 int memSum = 0;
109 if (initialized != 0 && counter >= count) {
110 counter -= count;
111 } else {
112 int cnt = count;
113 while (cnt-- > 0) {
114 T data = storage[index++];
115 int mem = data == null ? 0 : dataType.getMemory(data);
116 memSum += mem;
117 long delta = ((long) mem << WINDOW_SHIFT) - sum;
118 if (initialized == 0) {
119 if (++counter == WINDOW_SIZE) {
120 initialized = INIT_BIT;
121 }
122 sum = (sum * counter + delta + (counter >> 1)) / counter;
123 } else {
124 cnt -= counter;
125 long absDelta = delta >= 0 ? delta : -delta;
126 int magnitude = calculateMagnitude(sum, absDelta);
127 sum += ((delta >> (MAGNITUDE_LIMIT - magnitude)) + 1) >> 1;
128 counter += ((1 << magnitude) - 1) & COUNTER_MASK;
129
130 delta = ((long) counter << WINDOW_SHIFT) - skipSum;
131 skipSum += (delta + WINDOW_HALF_SIZE) >> WINDOW_SHIFT;
132 }
133 }
134 }
135 long updatedStatsData = updateStatsData(stats, statsData, counter, skipSum, initialized, sum, index, memSum);
136 return (getAverage(updatedStatsData) + MEMORY_POINTER) * count;
137 }
138
139 /**
140 * Calculates percentage of how many times actual calculation happened (vs. estimation)
141 * @param stats AtomicLong holding statistical data about the estimated sequence
142 * @return sampling percentage in range 0 - 100
143 */
144 public static int samplingPct(AtomicLong stats) {
145 long statsData = stats.get();
146 int count = (statsData & INIT_BIT) == 0 ? getCounter(statsData) : WINDOW_SIZE;
147 int total = getSkipSum(statsData) + count;
148 return (count * 100 + (total >> 1)) / total;
149 }
150
151 private static int calculateMagnitude(long sum, long absDelta) {
152 int magnitude = 0;
153 while (absDelta < sum && magnitude < MAGNITUDE_LIMIT) {
154 ++magnitude;
155 absDelta <<= 1;
156 }
157 return magnitude;
158 }
159
160 private static long updateStatsData(AtomicLong stats, long statsData,
161 int counter, int skipSum, long initialized, long sum,
162 int itemsCount, int itemsMem) {
163 return updateStatsData(stats, statsData,
164 constructStatsData(sum, initialized, skipSum, counter), itemsCount, itemsMem);
165 }
166
167 private static long constructStatsData(long sum, long initialized, int skipSum, int counter) {
168 return (sum << SUM_SHIFT) | initialized | ((long) skipSum << SKIP_SUM_SHIFT) | counter;
169 }
170
171 private static long updateStatsData(AtomicLong stats, long statsData, long updatedStatsData,
172 int itemsCount, int itemsMem) {
173 while (!stats.compareAndSet(statsData, updatedStatsData)) {
174 statsData = stats.get();
175 long sum = statsData >>> SUM_SHIFT;
176 if (itemsCount > 0) {
177 sum += itemsMem - ((sum * itemsCount + WINDOW_HALF_SIZE) >> WINDOW_SHIFT);
178 }
179 updatedStatsData = (sum << SUM_SHIFT) | (statsData & (INIT_BIT | SKIP_SUM_MASK | COUNTER_MASK));
180 }
181 return updatedStatsData;
182 }
183
184 private static int getCounter(long statsData) {
185 return (int)(statsData & COUNTER_MASK);
186 }
187
188 private static int getSkipSum(long statsData) {
189 return (int)((statsData >> SKIP_SUM_SHIFT) & SKIP_SUM_MASK);
190 }
191
192 private static int getAverage(long updatedStatsData) {
193 return (int)(updatedStatsData >>> (SUM_SHIFT + WINDOW_SHIFT));
194 }
195 }