04aaf4233796b41dee28031bee0cc101edd79d3e
[sixth-data.git] / src / main / java / eu / svjatoslav / sixth / data / store / file / VacuumContext.java
1 /*
2  * Sixth - System for data storage, computation, exploration and interaction.
3  * Copyright ©2012-2016, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.sixth.data.store.file;
11
12 public class VacuumContext {
13     private final FileDataStore vacuumContext;
14     private final int targetFragmentationPercent;
15     long analyzedBytesCount = 0;
16     long freeBytesCount = 0;
17     long lastRecordStartAddress;
18     long defragmentationStartAddress;
19
20     public VacuumContext(final FileDataStore fileDataStore,
21                          final long currentFreeAddress, final int targetFragmentationPercent) {
22
23         vacuumContext = fileDataStore;
24         lastRecordStartAddress = currentFreeAddress;
25         defragmentationStartAddress = currentFreeAddress;
26         this.targetFragmentationPercent = targetFragmentationPercent;
27     }
28
29     public void analyzeEntry(final EntryRecord record) {
30         final long bytesSinceLastEntry = lastRecordStartAddress
31                 - record.location;
32
33         final long freeSpace = bytesSinceLastEntry - record.length;
34         freeBytesCount += freeSpace;
35         analyzedBytesCount += freeSpace;
36
37         checkDefragmentationPointer(record.location + record.length);
38
39         analyzedBytesCount += record.length;
40         lastRecordStartAddress = record.location;
41     }
42
43     public void analyzeStartOfDataArea() {
44         freeBytesCount += lastRecordStartAddress
45                 - vacuumContext.metaData.getEntriesStorageAreaStart();
46
47         checkDefragmentationPointer(vacuumContext.metaData
48                 .getEntriesStorageAreaStart());
49     }
50
51     public void checkDefragmentationPointer(
52             final long defragmentationStartAddress) {
53
54         if (analyzedBytesCount == 0) {
55             this.defragmentationStartAddress = defragmentationStartAddress;
56             return;
57         }
58
59         final int fragmentationPercentage = (int) ((100L * freeBytesCount) / analyzedBytesCount);
60
61         if (fragmentationPercentage >= targetFragmentationPercent)
62             this.defragmentationStartAddress = defragmentationStartAddress;
63     }
64 }