Debian Codegraph @

src/main/org/h2/mvstore/RandomAccessStore.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.mvstore;
7
8 import java.nio.ByteBuffer;
9 import java.nio.charset.StandardCharsets;
10 import java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.Collections;
13 import java.util.Comparator;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.Map;
17 import java.util.PriorityQueue;
18 import java.util.Queue;
19
20 /**
21 * Class RandomAccessStore.
22 * <UL>
23 * <LI> 4/5/20 2:51 PM initial creation
24 * </UL>
25 *
26 * @author <a href="mailto:[email protected]">Andrei Tokar</a>
27 */
28 public abstract class RandomAccessStore extends FileStore<SFChunk>
29 {
30 /**
31 * The free spaces between the chunks. The first block to use is block 2
32 * (the first two blocks are the store header).
33 */
34 protected final FreeSpaceBitSet freeSpace = new FreeSpaceBitSet(2, BLOCK_SIZE);
35
36 /**
37 * Allocation mode:
38 * false - new chunk is always allocated at the end of file
39 * true - new chunk is allocated as close to the beginning of file, as possible
40 */
41 private volatile boolean reuseSpace = true;
42
43
44 private long reservedLow;
45 private long reservedHigh;
46
47
48 public RandomAccessStore(Map<String, Object> config) {
49 super(config);
50 }
51
52 @Override
53 protected final SFChunk createChunk(int newChunkId) {
54 return new SFChunk(newChunkId);
55 }
56
57 @Override
58 public SFChunk createChunk(String s) {
59 return new SFChunk(s);
60 }
61
62 @Override
63 protected SFChunk createChunk(Map<String, String> map) {
64 return new SFChunk(map);
65 }
66
67 /**
68 * Mark the space as in use.
69 *
70 * @param pos the position in bytes
71 * @param length the number of bytes
72 */
73 @Override
74 public void markUsed(long pos, int length) {
75 freeSpace.markUsed(pos, length);
76 }
77
78 /**
79 * Allocate a number of blocks and mark them as used.
80 *
81 * @param length the number of bytes to allocate
82 * @param reservedLow start block index of the reserved area (inclusive)
83 * @param reservedHigh end block index of the reserved area (exclusive),
84 * special value -1 means beginning of the infinite free area
85 * @return the start position in bytes
86 */
87 private long allocate(int length, long reservedLow, long reservedHigh) {
88 return freeSpace.allocate(length, reservedLow, reservedHigh);
89 }
90
91 /**
92 * Calculate starting position of the prospective allocation.
93 *
94 * @param blocks the number of blocks to allocate
95 * @param reservedLow start block index of the reserved area (inclusive)
96 * @param reservedHigh end block index of the reserved area (exclusive),
97 * special value -1 means beginning of the infinite free area
98 * @return the starting block index
99 */
100 private long predictAllocation(int blocks, long reservedLow, long reservedHigh) {
101 return freeSpace.predictAllocation(blocks, reservedLow, reservedHigh);
102 }
103
104 @Override
105 public boolean shouldSaveNow(int unsavedMemory, int autoCommitMemory) {
106 return unsavedMemory > autoCommitMemory;
107 }
108
109 private boolean isFragmented() {
110 return freeSpace.isFragmented();
111 }
112
113 @Override
114 public boolean isSpaceReused() {
115 return reuseSpace;
116 }
117
118 @Override
119 public void setReuseSpace(boolean reuseSpace) {
120 this.reuseSpace = reuseSpace;
121 }
122
123 @Override
124 protected void freeChunkSpace(Iterable<SFChunk> chunks) {
125 for (SFChunk chunk : chunks) {
126 freeChunkSpace(chunk);
127 }
128 assert validateFileLength(String.valueOf(chunks));
129 }
130
131 private void freeChunkSpace(SFChunk chunk) {
132 long start = chunk.block * BLOCK_SIZE;
133 int length = chunk.len * BLOCK_SIZE;
134 free(start, length);
135 }
136
137 /**
138 * Mark the space as free.
139 *
140 * @param pos the position in bytes
141 * @param length the number of bytes
142 */
143 protected void free(long pos, int length) {
144 freeSpace.free(pos, length);
145 }
146
147 @Override
148 public int getFillRate() {
149 saveChunkLock.lock();
150 try {
151 return freeSpace.getFillRate();
152 } finally {
153 saveChunkLock.unlock();
154 }
155 }
156
157 @Override
158 protected final boolean validateFileLength(String msg) {
159 assert saveChunkLock.isHeldByCurrentThread();
160 assert getFileLengthInUse() == measureFileLengthInUse() :
161 getFileLengthInUse() + " != " + measureFileLengthInUse() + " " + msg;
162 return true;
163 }
164
165 private long measureFileLengthInUse() {
166 assert saveChunkLock.isHeldByCurrentThread();
167 long size = 2;
168 for (SFChunk c : getChunks().values()) {
169 if (c.isAllocated()) {
170 size = Math.max(size, c.block + c.len);
171 }
172 }
173 return size * BLOCK_SIZE;
174 }
175
176 long getFirstFree() {
177 return freeSpace.getFirstFree();
178 }
179
180 long getFileLengthInUse() {
181 return freeSpace.getLastFree();
182 }
183
184 @Override
185 protected void readStoreHeader(boolean recoveryMode) {
186 SFChunk newest = null;
187 boolean assumeCleanShutdown = true;
188 boolean validStoreHeader = false;
189 // find out which chunk and version are the newest
190 // read the first two blocks
191 ByteBuffer fileHeaderBlocks = readFully((SFChunk)null, 0, 2 * FileStore.BLOCK_SIZE);
192 byte[] buff = new byte[FileStore.BLOCK_SIZE];
193 for (int i = 0; i <= FileStore.BLOCK_SIZE; i += FileStore.BLOCK_SIZE) {
194 fileHeaderBlocks.get(buff);
195 // the following can fail for various reasons
196 try {
197 HashMap<String, String> m = DataUtils.parseChecksummedMap(buff);
198 if (m == null) {
199 assumeCleanShutdown = false;
200 continue;
201 }
202 long version = DataUtils.readHexLong(m, FileStore.HDR_VERSION, 0);
203 // if both header blocks do agree on version
204 // we'll continue on happy path - assume that previous shutdown was clean
205 assumeCleanShutdown = assumeCleanShutdown && (newest == null || version == newest.version);
206 if (newest == null || version > newest.version) {
207 validStoreHeader = true;
208 storeHeader.putAll(m);
209 int chunkId = DataUtils.readHexInt(m, FileStore.HDR_CHUNK, 0);
210 long block = DataUtils.readHexLong(m, FileStore.HDR_BLOCK, 2);
211 SFChunk test = readChunkHeaderAndFooter(block, chunkId);
212 if (test != null) {
213 newest = test;
214 }
215 }
216 } catch (Exception ignore) {
217 assumeCleanShutdown = false;
218 }
219 }
220
221 if (!validStoreHeader) {
222 throw DataUtils.newMVStoreException(
223 DataUtils.ERROR_FILE_CORRUPT,
224 "Store header is corrupt: {0}", this);
225 }
226
227 processCommonHeaderAttributes();
228
229 assumeCleanShutdown = assumeCleanShutdown && newest != null && !recoveryMode;
230 if (assumeCleanShutdown) {
231 assumeCleanShutdown = DataUtils.readHexInt(storeHeader, FileStore.HDR_CLEAN, 0) != 0;
232 }
233 // assert getChunks().size() <= 1 : getChunks().size();
234
235 long fileSize = size();
236 long blocksInStore = fileSize / FileStore.BLOCK_SIZE;
237
238 Comparator<SFChunk> chunkComparator = (one, two) -> {
239 int result = Long.compare(two.version, one.version);
240 if (result == 0) {
241 // out of two copies of the same chunk we prefer the one
242 // close to the beginning of file (presumably later version)
243 result = Long.compare(one.block, two.block);
244 }
245 return result;
246 };
247
248 Map<Long,SFChunk> validChunksByLocation = new HashMap<>();
249 if (assumeCleanShutdown) {
250 // quickly check latest 20 chunks referenced in meta table
251 Queue<SFChunk> chunksToVerify = new PriorityQueue<>(20, Collections.reverseOrder(chunkComparator));
252 try {
253 setLastChunk(newest);
254 // load the chunk metadata: although meta's root page resides in the lastChunk,
255 // traversing meta map might recursively load another chunk(s)
256 for (SFChunk c : getChunksFromLayoutMap()) {
257 // might be there already, due to meta traversal
258 // see readPage() ... getChunkIfFound()
259 chunksToVerify.offer(c);
260 if (chunksToVerify.size() == 20) {
261 chunksToVerify.poll();
262 }
263 }
264 SFChunk c;
265 while (assumeCleanShutdown && (c = chunksToVerify.poll()) != null) {
266 SFChunk test = readChunkHeaderAndFooter(c.block, c.id);
267 assumeCleanShutdown = test != null;
268 if (assumeCleanShutdown) {
269 validChunksByLocation.put(test.block, test);
270 }
271 }
272 } catch(IllegalStateException ignored) {
273 assumeCleanShutdown = false;
274 }
275 } else {
276 SFChunk tailChunk = discoverChunk(blocksInStore);
277 if (tailChunk != null) {
278 blocksInStore = tailChunk.block; // for a possible full scan later on
279 validChunksByLocation.put(blocksInStore, tailChunk);
280 if (newest == null || tailChunk.version > newest.version) {
281 newest = tailChunk;
282 }
283 }
284 if (newest != null) {
285 // read the chunk header and footer,
286 // and follow the chain of next chunks
287 while (true) {
288 validChunksByLocation.put(newest.block, newest);
289 if (newest.next == 0 || newest.next >= blocksInStore) {
290 // no (valid) next
291 break;
292 }
293 SFChunk test = readChunkHeaderAndFooter(newest.next, newest.id + 1);
294 if (test == null || test.version <= newest.version) {
295 break;
296 }
297 newest = test;
298 }
299 }
300 }
301
302 if (!assumeCleanShutdown) {
303 // now we know, that previous shutdown did not go well and file
304 // is possibly corrupted but there is still hope for a quick
305 // recovery
306 boolean quickRecovery = !recoveryMode &&
307 findLastChunkWithCompleteValidChunkSet(chunkComparator, validChunksByLocation, false);
308 if (!quickRecovery) {
309 // scan whole file and try to fetch chunk header and/or footer out of every block
310 // matching pairs with nothing in-between are considered as valid chunk
311 long block = blocksInStore;
312 SFChunk tailChunk;
313 while ((tailChunk = discoverChunk(block)) != null) {
314 block = tailChunk.block;
315 validChunksByLocation.put(block, tailChunk);
316 }
317
318 if (!findLastChunkWithCompleteValidChunkSet(chunkComparator, validChunksByLocation, true)
319 && hasPersistentData()) {
320 throw DataUtils.newMVStoreException(
321 DataUtils.ERROR_FILE_CORRUPT,
322 "File is corrupted - unable to recover a valid set of chunks");
323 }
324 }
325 }
326
327 clear();
328 // build the free space list
329 for (SFChunk c : getChunks().values()) {
330 if (c.isAllocated()) {
331 long start = c.block * FileStore.BLOCK_SIZE;
332 int length = c.len * FileStore.BLOCK_SIZE;
333 markUsed(start, length);
334 }
335 if (!c.isLive()) {
336 registerDeadChunk(c);
337 }
338 }
339 assert validateFileLength("on open");
340 }
341
342 @Override
343 protected void initializeStoreHeader(long time) {
344 initializeCommonHeaderAttributes(time);
345 writeStoreHeader();
346 }
347
348 @Override
349 protected final void allocateChunkSpace(SFChunk chunk, WriteBuffer buff) {
350 long reservedLow = this.reservedLow;
351 long reservedHigh = this.reservedHigh > 0 ? this.reservedHigh : isSpaceReused() ? 0 : getAfterLastBlock();
352 long filePos = allocate(buff.limit(), reservedLow, reservedHigh);
353 // calculate and set the likely next position
354 if (reservedLow > 0 || reservedHigh == reservedLow) {
355 chunk.next = predictAllocation(chunk.len, 0, 0);
356 } else {
357 // just after this chunk
358 chunk.next = 0;
359 }
360 chunk.block = filePos / BLOCK_SIZE;
361 }
362
363 @Override
364 protected final void writeChunk(SFChunk chunk, WriteBuffer buffer) {
365 long filePos = chunk.block * BLOCK_SIZE;
366 writeFully(chunk, filePos, buffer.getBuffer());
367
368 // end of the used space is not necessarily the end of the file
369 boolean storeAtEndOfFile = filePos + buffer.limit() >= size();
370 boolean shouldWriteStoreHeader = shouldWriteStoreHeader(chunk, storeAtEndOfFile);
371 lastChunk = chunk;
372 if (shouldWriteStoreHeader) {
373 writeStoreHeader();
374 }
375 if (!storeAtEndOfFile) {
376 // may only shrink after the store header was written
377 shrinkStoreIfPossible(1);
378 }
379 }
380
381 private boolean shouldWriteStoreHeader(SFChunk c, boolean storeAtEndOfFile) {
382 // whether we need to write the store header
383 boolean writeStoreHeader = false;
384 if (!storeAtEndOfFile) {
385 SFChunk chunk = lastChunk;
386 if (chunk == null) {
387 writeStoreHeader = true;
388 } else if (chunk.next != c.block) {
389 // the last prediction did not matched
390 writeStoreHeader = true;
391 } else {
392 long headerVersion = DataUtils.readHexLong(storeHeader, HDR_VERSION, 0);
393 if (chunk.version - headerVersion > 20) {
394 // we write after at least every 20 versions
395 writeStoreHeader = true;
396 } else {
397 for (int chunkId = DataUtils.readHexInt(storeHeader, HDR_CHUNK, 0);
398 !writeStoreHeader && chunkId <= chunk.id; ++chunkId) {
399 // one of the chunks in between
400 // was removed
401 writeStoreHeader = !getChunks().containsKey(chunkId);
402 }
403 }
404 }
405 }
406
407 if (storeHeader.remove(HDR_CLEAN) != null) {
408 writeStoreHeader = true;
409 }
410 return writeStoreHeader;
411 }
412
413 @Override
414 protected final void writeCleanShutdownMark() {
415 shrinkStoreIfPossible(0);
416 storeHeader.put(HDR_CLEAN, 1);
417 writeStoreHeader();
418 }
419
420 @Override
421 protected final void adjustStoreToLastChunk() {
422 storeHeader.put(HDR_CLEAN, 1);
423 writeStoreHeader();
424 readStoreHeader(false);
425 }
426
427 /**
428 * Compact store file, that is, compact blocks that have a low
429 * fill rate, and move chunks next to each other. This will typically
430 * shrink the file. Changes are flushed to the file, and old
431 * chunks are overwritten.
432 *
433 * @param thresholdFillRate do not compact if store fill rate above this value (0-100)
434 * @param maxCompactTime the maximum time in milliseconds to compact
435 * @param maxWriteSize the maximum amount of data to be written as part of this call
436 */
437 @Override
438 protected void compactStore(int thresholdFillRate, long maxCompactTime, int maxWriteSize, MVStore mvStore) {
439 setRetentionTime(0);
440 long stopAt = System.nanoTime() + maxCompactTime * 1_000_000L;
441 while (compact(thresholdFillRate, maxWriteSize)) {
442 sync();
443 compactMoveChunks(thresholdFillRate, maxWriteSize, mvStore);
444 if (System.nanoTime() - stopAt > 0L) {
445 break;
446 }
447 }
448 }
449
450 /**
451 * Compact the store by moving all chunks next to each other, if there is
452 * free space between chunks. This might temporarily increase the file size.
453 * Chunks are overwritten irrespective of the current retention time. Before
454 * overwriting chunks and before resizing the file, syncFile() is called.
455 *
456 * @param targetFillRate do nothing if the file store fill rate is higher
457 * than this
458 * @param moveSize the number of bytes to move
459 * @param mvStore owner of this store
460 */
461 public void compactMoveChunks(int targetFillRate, long moveSize, MVStore mvStore) {
462 if (isSpaceReused()) {
463 mvStore.executeFilestoreOperation(() -> {
464 dropUnusedChunks();
465 saveChunkLock.lock();
466 try {
467 if (hasPersistentData() && getFillRate() <= targetFillRate) {
468 compactMoveChunks(moveSize);
469 }
470 } finally {
471 saveChunkLock.unlock();
472 }
473 });
474 }
475 }
476
477 private void compactMoveChunks(long moveSize) {
478 long start = getFirstFree() / FileStore.BLOCK_SIZE;
479 Iterable<SFChunk> chunksToMove = findChunksToMove(start, moveSize);
480 if (chunksToMove != null) {
481 compactMoveChunks(chunksToMove);
482 }
483 }
484
485 private Iterable<SFChunk> findChunksToMove(long startBlock, long moveSize) {
486 long maxBlocksToMove = moveSize / FileStore.BLOCK_SIZE;
487 Iterable<SFChunk> result = null;
488 if (maxBlocksToMove > 0) {
489 PriorityQueue<SFChunk> queue = new PriorityQueue<>(getChunks().size() / 2 + 1,
490 (o1, o2) -> {
491 // instead of selection just closest to beginning of the file,
492 // pick smaller chunk(s) which sit in between bigger holes
493 int res = Integer.compare(o2.collectPriority, o1.collectPriority);
494 if (res != 0) {
495 return res;
496 }
497 return Long.signum(o2.block - o1.block);
498 });
499 long size = 0;
500 for (SFChunk chunk : getChunks().values()) {
501 if (chunk.isAllocated() && chunk.block > startBlock) {
502 chunk.collectPriority = getMovePriority(chunk);
503 queue.offer(chunk);
504 size += chunk.len;
505 while (size > maxBlocksToMove) {
506 Chunk<?> removed = queue.poll();
507 if (removed == null) {
508 break;
509 }
510 size -= removed.len;
511 }
512 }
513 }
514 if (!queue.isEmpty()) {
515 ArrayList<SFChunk> list = new ArrayList<>(queue);
516 list.sort(Chunk.PositionComparator.instance());
517 result = list;
518 }
519 }
520 return result;
521 }
522
523 private int getMovePriority(SFChunk chunk) {
524 return getMovePriority((int)chunk.block);
525 }
526
527 private void compactMoveChunks(Iterable<SFChunk> move) {
528 assert saveChunkLock.isHeldByCurrentThread();
529 if (move != null) {
530 // this will ensure better recognition of the last chunk
531 // in case of power failure, since we are going to move older chunks
532 // to the end of the file
533 writeStoreHeader();
534 sync();
535
536 Iterator<SFChunk> iterator = move.iterator();
537 assert iterator.hasNext();
538 long leftmostBlock = iterator.next().block;
539 long originalBlockCount = getAfterLastBlock();
540 // we need to ensure that chunks moved within the following loop
541 // do not overlap with space just released by chunks moved before them,
542 // hence the need to reserve this area [leftmostBlock, originalBlockCount)
543 for (SFChunk chunk : move) {
544 moveChunk(chunk, leftmostBlock, originalBlockCount);
545 }
546 // update the metadata (hopefully within the file)
547 store(leftmostBlock, originalBlockCount);
548 sync();
549
550 SFChunk chunkToMove = lastChunk;
551 assert chunkToMove != null;
552 long postEvacuationBlockCount = getAfterLastBlock();
553
554 boolean chunkToMoveIsAlreadyInside = chunkToMove.block < leftmostBlock;
555 boolean movedToEOF = !chunkToMoveIsAlreadyInside;
556 // move all chunks, which previously did not fit before reserved area
557 // now we can re-use previously reserved area [leftmostBlock, originalBlockCount),
558 // but need to reserve [originalBlockCount, postEvacuationBlockCount)
559 for (SFChunk c : move) {
560 if (c.block >= originalBlockCount &&
561 moveChunk(c, originalBlockCount, postEvacuationBlockCount)) {
562 assert c.block < originalBlockCount;
563 movedToEOF = true;
564 }
565 }
566 assert postEvacuationBlockCount >= getAfterLastBlock();
567
568 if (movedToEOF) {
569 boolean moved = moveChunkInside(chunkToMove, originalBlockCount);
570
571 // store a new chunk with updated metadata (hopefully within a file)
572 store(originalBlockCount, postEvacuationBlockCount);
573 sync();
574 // if chunkToMove did not fit within originalBlockCount (move is
575 // false), and since now previously reserved area
576 // [originalBlockCount, postEvacuationBlockCount) also can be
577 // used, lets try to move that chunk into this area, closer to
578 // the beginning of the file
579 long lastBoundary = moved || chunkToMoveIsAlreadyInside ?
580 postEvacuationBlockCount : chunkToMove.block;
581 moved = !moved && moveChunkInside(chunkToMove, lastBoundary);
582 if (moveChunkInside(lastChunk, lastBoundary) || moved) {
583 store(lastBoundary, -1);
584 }
585 }
586
587 shrinkStoreIfPossible(0);
588 sync();
589 }
590 }
591
592 private void writeStoreHeader() {
593 StringBuilder buff = new StringBuilder(112);
594 if (hasPersistentData()) {
595 storeHeader.put(HDR_BLOCK, lastChunk.block);
596 storeHeader.put(HDR_CHUNK, lastChunk.id);
597 storeHeader.put(HDR_VERSION, lastChunk.version);
598 }
599 DataUtils.appendMap(buff, storeHeader);
600 byte[] bytes = buff.toString().getBytes(StandardCharsets.ISO_8859_1);
601 int checksum = DataUtils.getFletcher32(bytes, 0, bytes.length);
602 DataUtils.appendMap(buff, HDR_FLETCHER, checksum);
603 buff.append('\n');
604 bytes = buff.toString().getBytes(StandardCharsets.ISO_8859_1);
605 ByteBuffer header = ByteBuffer.allocate(2 * BLOCK_SIZE);
606 header.put(bytes);
607 header.position(BLOCK_SIZE);
608 header.put(bytes);
609 header.rewind();
610 writeFully(null, 0, header);
611 }
612
613 private void store(long reservedLow, long reservedHigh) {
614 this.reservedLow = reservedLow;
615 this.reservedHigh = reservedHigh;
616 saveChunkLock.unlock();
617 try {
618 store();
619 } finally {
620 saveChunkLock.lock();
621 this.reservedLow = 0;
622 this.reservedHigh = 0;
623 }
624 }
625
626 private boolean moveChunkInside(SFChunk chunkToMove, long boundary) {
627 boolean res = chunkToMove.block >= boundary &&
628 predictAllocation(chunkToMove.len, boundary, -1) < boundary &&
629 moveChunk(chunkToMove, boundary, -1);
630 assert !res || chunkToMove.block + chunkToMove.len <= boundary;
631 return res;
632 }
633
634 /**
635 * Move specified chunk into free area of the file. "Reserved" area
636 * specifies file interval to be avoided, when un-allocated space will be
637 * chosen for a new chunk's location.
638 *
639 * @param chunk to move
640 * @param reservedAreaLow low boundary of reserved area, inclusive
641 * @param reservedAreaHigh high boundary of reserved area, exclusive
642 * @return true if block was moved, false otherwise
643 */
644 private boolean moveChunk(SFChunk chunk, long reservedAreaLow, long reservedAreaHigh) {
645 // ignore if already removed during the previous store operations
646 // those are possible either as explicit commit calls
647 // or from meta map updates at the end of this method
648 if (!getChunks().containsKey(chunk.id)) {
649 return false;
650 }
651 long start = chunk.block * FileStore.BLOCK_SIZE;
652 int length = chunk.len * FileStore.BLOCK_SIZE;
653 long pos = allocate(length, reservedAreaLow, reservedAreaHigh);
654 long block = pos / FileStore.BLOCK_SIZE;
655 // in the absence of a reserved area,
656 // block should always move closer to the beginning of the file
657 assert reservedAreaHigh > 0 || block <= chunk.block : block + " " + chunk;
658 ByteBuffer readBuff = readFully(chunk, start, length);
659 writeFully(null, pos, readBuff);
660 free(start, length);
661 // can not set chunk's new block/len until it's fully written at new location,
662 // because concurrent reader can pick it up prematurely,
663 chunk.block = block;
664 chunk.next = 0;
665 saveChunkMetadataChanges(chunk);
666 return true;
667 }
668
669 /**
670 * Shrink the store if possible, and if at least a given percentage can be
671 * saved.
672 *
673 * @param minPercent the minimum percentage to save
674 */
675 @Override
676 protected void shrinkStoreIfPossible(int minPercent) {
677 assert saveChunkLock.isHeldByCurrentThread();
678 long result = getFileLengthInUse();
679 assert result == measureFileLengthInUse() : result + " != " + measureFileLengthInUse();
680 shrinkIfPossible(minPercent);
681 }
682
683 private void shrinkIfPossible(int minPercent) {
684 if (isReadOnly()) {
685 return;
686 }
687 long end = getFileLengthInUse();
688 long fileSize = size();
689 if (end >= fileSize) {
690 return;
691 }
692 if (minPercent > 0 && fileSize - end < BLOCK_SIZE) {
693 return;
694 }
695 int savedPercent = (int) (100 - (end * 100 / fileSize));
696 if (savedPercent < minPercent) {
697 return;
698 }
699 sync();
700 truncate(end);
701 }
702
703 @Override
704 protected void doHousekeeping(MVStore mvStore) throws InterruptedException {
705 int autoCommitMemory = mvStore.getAutoCommitMemory();
706 int fillRate = getFillRate();
707 if (isFragmented() && fillRate < getAutoCompactFillRate()) {
708
709 mvStore.tryExecuteUnderStoreLock(() -> {
710 int moveSize = autoCommitMemory;
711 if (isIdle()) {
712 moveSize *= 4;
713 }
714 compactMoveChunks(101, moveSize, mvStore);
715 return true;
716 });
717 } else if (fillRate >= getAutoCompactFillRate() && hasPersistentData()) {
718 int chunksFillRate = getRewritableChunksFillRate();
719 int _chunksFillRate = isIdle() ? 100 - (100 - chunksFillRate) / 2 : chunksFillRate;
720 if (_chunksFillRate < getTargetFillRate()) {
721 mvStore.tryExecuteUnderStoreLock(() -> {
722 int writeLimit = autoCommitMemory * fillRate / Math.max(_chunksFillRate, 1);
723 if (!isIdle()) {
724 writeLimit /= 4;
725 }
726 if (rewriteChunks(writeLimit, _chunksFillRate)) {
727 dropUnusedChunks();
728 }
729 return true;
730 });
731 }
732 }
733 }
734
735 private int getTargetFillRate() {
736 int targetRate = getAutoCompactFillRate();
737 // use a lower fill rate if there were any file operations since the last time
738 if (!isIdle()) {
739 targetRate /= 2;
740 }
741 return targetRate;
742 }
743
744 protected abstract void truncate(long size);
745
746 /**
747 * Mark the file as empty.
748 */
749 @Override
750 public void clear() {
751 freeSpace.clear();
752 }
753
754 /**
755 * Calculates relative "priority" for chunk to be moved.
756 *
757 * @param block where chunk starts
758 * @return priority, bigger number indicate that chunk need to be moved sooner
759 */
760 public int getMovePriority(int block) {
761 return freeSpace.getMovePriority(block);
762 }
763
764 /**
765 * Get the index of the first block after last occupied one.
766 * It marks the beginning of the last (infinite) free space.
767 *
768 * @return block index
769 */
770 private long getAfterLastBlock() {
771 assert saveChunkLock.isHeldByCurrentThread();
772 return getAfterLastBlock_();
773 }
774
775 protected long getAfterLastBlock_() {
776 return freeSpace.getAfterLastBlock();
777 }
778
779 @Override
780 public Collection<SFChunk> getRewriteCandidates() {
781 return isSpaceReused() ? null : Collections.emptyList();
782 }
783 }