Class FileStore<C extends Chunk<C>>
- Direct Known Subclasses:
AppendOnlyMultiFileStore,RandomAccessStore
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected CThe newest chunk.static final StringThe key for the entry within "layout" map, which contains id of "meta" map.static final intprotected final AtomicLongThe number of read bytes.protected final AtomicLongThe number of read operations.protected final booleanprotected final ReentrantLockprotected final AtomicLongThe number of written bytes.protected final AtomicLongThe number of write operations. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidaccountForRemovedPage(long pos, long version, boolean pinned, int pageNo) Remove a page.protected abstract voidMake persistent changes after lastChunk was resetprotected abstract voidallocateChunkSpace(C chunk, WriteBuffer buff) Allocate logical space and assign position of the buffer within the store.abstract voidbackup(ZipOutputStream out) final voidvoidclear()voidclose()booleancompact(int targetFillRate, int write) Try to increase the fill rate by re-writing partially full chunks.protected abstract voidcompactStore(int thresholdFillRate, long maxCompactTime, int maxWriteSize, MVStore mvStore) Compact store file, that is, compact blocks that have a low fill rate, and move chunks next to each other.voidcompactStore(long maxCompactTime) protected abstract CcreateChunk(int id) abstract CBuild a Chunk from the given string.protected abstract CcreateChunk(Map<String, String> map) final booleanderegisterMapRoot(int mapId) Performs final stage of map removal - delete root location info from the layout map.protected final CdiscoverChunk(long block) Discover a valid chunk, searching file backwards from the given blockprotected abstract voiddoHousekeeping(MVStore mvStore) final voidvoidexecuteFileStoreOperation(Runnable operation) protected final booleanfindLastChunkWithCompleteValidChunkSet(Comparator<C> chunkComparator, Map<Long, C> validChunksByLocation, boolean afterFullScan) protected abstract voidfreeChunkSpace(Iterable<C> chunks) Mark the space occupied by specified chunks as free.final intGet the auto-commit delay.protected final intintintGet the maximum cache size, in MB.intGet the amount of memory used for caching, in MB.protected final ConcurrentMap<Integer, C> intGet the current fill rate (percentage of used space in the file).longThe time the store was created, in milliseconds since 1970.intGet the default retention time for this store in milliseconds.Get the file name.abstract intGet this store's layout map.final longfinal intgetMetaMapId(IntSupplier nextIdSupplier) protected final MVStorelongGet the number of read bytes since this store was opened.longGet the number of read operations since this store was opened.final intprotected Collection<C> final longgetRootPos(int mapId) Get "position" of the root page for the specified mapGet the store header.intGet a buffer for writing.longGet the number of write operations since this store was opened.final booleanhasChangesSince(long lastStoredVersion) Check whether there are any unsaved changes since specified version.protected final booleanprotected final voidprotected final voidinitializeCommonHeaderAttributes(long time) protected abstract voidinitializeStoreHeader(long time) protected final booleanisIdle()final booleanisKnownVersion(long version) Check whether all data can be read from this version.booleanfinal booleanisRegularMap(MVMap<?, ?> map) booleanfinal longprotected abstract voidmarkUsed(long pos, int length) Mark the space as in use.abstract voidvoidpopulateInfo(BiConsumer<String, String> consumer) protected final voidprotected final CreadChunkFooter(long block) Try to read a chunk footer.protected final CreadChunkHeaderAndFooter(long block, int expectedId) Read a chunk header and footer, and verify the stored data is consistent.protected final CreadChunkHeaderOptionally(long block) protected final CreadChunkHeaderOptionally(long block, int expectedId) abstract ByteBufferRead data from the store.protected final ByteBufferreadFully(FileChannel file, long pos, int len) protected abstract voidreadStoreHeader(boolean recoveryMode) protected final voidregisterDeadChunk(C chunk) voidRelease a buffer for writing.protected booleanrewriteChunks(int writeLimit, int targetFillRate) final voidrollbackTo(long version) voidsaveChunkMetadataChanges(C chunk) Store chunk's serialized metadata as an entry in a layout map.final voidsetAutoCommitDelay(int millis) Set the maximum delay in milliseconds to auto-commit changes.voidsetCacheSize(int mb) Set the read cache size in MB.protected final voidsetLastChunk(C last) final voidsetRetentionTime(int ms) How long to retain old, persisted chunks, in milliseconds.voidsetReuseSpace(boolean reuseSpace) protected final voidsetSize(long size) abstract booleanshouldSaveNow(int unsavedMemory, int autoCommitMemory) Decision about autocommit is delegated to storeprotected abstract voidshrinkStoreIfPossible(int minPercent) Shrink store if possible, and if at least a given percentage can be saved.longsize()Get the file size.start()final voidstop(long allowedCompactionTime) protected final voidstore()voidsync()protected abstract booleanvalidateFileLength(String msg) protected abstract voidwriteChunk(C chunk, WriteBuffer buffer) Write buffer associated with chunk into store at chunk's allocated positionprotected voidprotected abstract voidPerforms final preparation before store is closed normallyprotected abstract voidwriteFully(C chunk, long pos, ByteBuffer src) Write to the file.
-
Field Details
-
META_ID_KEY
The key for the entry within "layout" map, which contains id of "meta" map. Entry value (hex encoded) is usually equal to 1, unless it's a legacy (upgraded) database and id 1 has been taken already by another map.- See Also:
-
readCount
The number of read operations. -
readBytes
The number of read bytes. -
writeCount
The number of write operations. -
writeBytes
The number of written bytes. -
lastChunk
The newest chunk. If nothing was stored yet, this field is not set. -
saveChunkLock
-
storeHeader
-
recoveryMode
protected final boolean recoveryMode -
PIPE_LENGTH
public static final int PIPE_LENGTH- See Also:
-
-
Constructor Details
-
FileStore
-
-
Method Details
-
open
-
open
-
init
-
bind
-
stop
public final void stop(long allowedCompactionTime) -
close
public void close() -
getMetaMapId
-
getLayoutMap
Get this store's layout map. This data is for informational purposes only. The data is subject to change in future versions.The data in this map should not be modified (changing system data may corrupt the store).
The layout map contains the following entries:
chunk.{chunkId} = {chunk metadata} root.{mapId} = {root position}- Returns:
- the metadata map
-
isRegularMap
-
getRootPos
public final long getRootPos(int mapId) Get "position" of the root page for the specified map- Parameters:
mapId- to get root position for- Returns:
- opaque "position" value, that should be used to read the page
-
deregisterMapRoot
public final boolean deregisterMapRoot(int mapId) Performs final stage of map removal - delete root location info from the layout map. Specified map is supposedly closed, is anonymous and has no outstanding usage by now.- Parameters:
mapId- to deregister- Returns:
- true if root was removed, false if it is not there
-
hasChangesSince
public final boolean hasChangesSince(long lastStoredVersion) Check whether there are any unsaved changes since specified version.- Parameters:
lastStoredVersion- version to take as a base for changes- Returns:
- if there are any changes
-
lastChunkVersion
public final long lastChunkVersion() -
getMaxPageSize
public final long getMaxPageSize() -
getRetentionTime
public final int getRetentionTime() -
setRetentionTime
public final void setRetentionTime(int ms) How long to retain old, persisted chunks, in milliseconds. Chunks that are older may be overwritten once they contain no live data.The default value is 45000 (45 seconds) when using the default file store. It is assumed that a file system and hard disk will flush all write buffers within this time. Using a lower value might be dangerous, unless the file system and hard disk flush the buffers earlier. To manually flush the buffers, use
MVStore.getFile().force(true), however please note that according to various tests this does not always work as expected depending on the operating system and hardware.The retention time needs to be long enough to allow reading old chunks while traversing over the entries of a map.
This setting is not persisted.
- Parameters:
ms- how many milliseconds to retain old chunks (0 to overwrite them as early as possible)
-
shouldSaveNow
public abstract boolean shouldSaveNow(int unsavedMemory, int autoCommitMemory) Decision about autocommit is delegated to store- Parameters:
unsavedMemory- amount of unsaved memory, so farautoCommitMemory- configured limit on amount of unsaved memory- Returns:
- true if commit should happen now
-
getAutoCommitDelay
public final int getAutoCommitDelay()Get the auto-commit delay.- Returns:
- the delay in milliseconds, or 0 if auto-commit is disabled.
-
setAutoCommitDelay
public final void setAutoCommitDelay(int millis) Set the maximum delay in milliseconds to auto-commit changes.To disable auto-commit, set the value to 0. In this case, changes are only committed when explicitly calling commit.
The default is 1000, meaning all changes are committed after at most one second.
- Parameters:
millis- the maximum delay
-
isKnownVersion
public final boolean isKnownVersion(long version) Check whether all data can be read from this version. This requires that all chunks referenced by this version are still available (not overwritten).- Parameters:
version- the version- Returns:
- true if all data can be read
-
rollbackTo
public final void rollbackTo(long version) -
initializeCommonHeaderAttributes
protected final void initializeCommonHeaderAttributes(long time) -
processCommonHeaderAttributes
protected final void processCommonHeaderAttributes() -
hasPersistentData
protected final boolean hasPersistentData() -
isIdle
protected final boolean isIdle() -
setLastChunk
-
registerDeadChunk
-
dropUnusedChunks
public final void dropUnusedChunks() -
writeFully
Write to the file.- Parameters:
chunk- to writepos- the write positionsrc- the source buffer
-
readFully
Read data from the store.- Parameters:
chunk- that owns data to be readpos- the read "position"len- the number of bytes to read- Returns:
- the byte buffer with data requested
-
readFully
-
allocateChunkSpace
Allocate logical space and assign position of the buffer within the store.- Parameters:
chunk- to allocate space forbuff- to allocate space for
-
writeChunk
Write buffer associated with chunk into store at chunk's allocated position- Parameters:
chunk- chunk to writebuffer- to write
-
writeCleanShutdownMark
protected abstract void writeCleanShutdownMark()Performs final preparation before store is closed normally -
adjustStoreToLastChunk
protected abstract void adjustStoreToLastChunk()Make persistent changes after lastChunk was reset -
getStoreHeader
Get the store header. This data is for informational purposes only. The data is subject to change in future versions. The data should not be modified (doing so may corrupt the store).- Returns:
- the store header
-
createChunk
-
createChunk
Build a Chunk from the given string.- Parameters:
s- the string- Returns:
- the Chunk created
-
createChunk
-
writeCleanShutdown
protected void writeCleanShutdown() -
saveChunkMetadataChanges
Store chunk's serialized metadata as an entry in a layout map. Key for this entry would be "chunk.<id>"- Parameters:
chunk- to save
-
freeChunkSpace
Mark the space occupied by specified chunks as free.- Parameters:
chunks- chunks to be processed
-
validateFileLength
-
compact
public boolean compact(int targetFillRate, int write) Try to increase the fill rate by re-writing partially full chunks. Chunks with a low number of live items are re-written.If the current fill rate is higher than the target fill rate, nothing is done.
Please note this method will not necessarily reduce the file size, as empty chunks are not overwritten.
Only data of open maps can be moved. For maps that are not open, the old chunk is still referenced. Therefore, it is recommended to open all maps before calling this method.
- Parameters:
targetFillRate- the minimum percentage of live entrieswrite- the minimum number of bytes to write- Returns:
- if any chunk was re-written
-
compactStore
public void compactStore(long maxCompactTime) -
compactStore
protected abstract void compactStore(int thresholdFillRate, long maxCompactTime, int maxWriteSize, MVStore mvStore) Compact store file, that is, compact blocks that have a low fill rate, and move chunks next to each other. This will typically shrink the file. Changes are flushed to the file, and old chunks are overwritten.- Parameters:
thresholdFillRate- do not compact if store fill rate above this value (0-100)maxCompactTime- the maximum time in milliseconds to compactmaxWriteSize- the maximum amount of data to be written as part of this callmvStore- that owns this FileStore
-
doHousekeeping
- Throws:
InterruptedException
-
start
-
initializeStoreHeader
protected abstract void initializeStoreHeader(long time) -
readStoreHeader
protected abstract void readStoreHeader(boolean recoveryMode) -
discoverChunk
Discover a valid chunk, searching file backwards from the given block- Parameters:
block- to start search from (found chunk footer should be no further than block-1)- Returns:
- valid chunk or null if none found
-
findLastChunkWithCompleteValidChunkSet
protected final boolean findLastChunkWithCompleteValidChunkSet(Comparator<C> chunkComparator, Map<Long, C> validChunksByLocation, boolean afterFullScan) -
getChunksFromLayoutMap
-
readChunkHeaderOptionally
-
readChunkHeaderOptionally
-
getWriteBuffer
Get a buffer for writing. This caller must synchronize on the store before calling the method and until after using the buffer.- Returns:
- the buffer
-
releaseWriteBuffer
Release a buffer for writing. This caller must synchronize on the store before calling the method and until after using the buffer.- Parameters:
buff- the buffer than can be re-used
-
getCreationTime
public long getCreationTime()The time the store was created, in milliseconds since 1970.- Returns:
- creation time
-
getAutoCompactFillRate
protected final int getAutoCompactFillRate() -
sync
public void sync() -
getFillRate
public abstract int getFillRate() -
shrinkStoreIfPossible
protected abstract void shrinkStoreIfPossible(int minPercent) Shrink store if possible, and if at least a given percentage can be saved.- Parameters:
minPercent- the minimum percentage to save
-
size
public long size()Get the file size.- Returns:
- the file size
-
setSize
protected final void setSize(long size) -
getWriteCount
public long getWriteCount()Get the number of write operations since this store was opened. For file based stores, this is the number of file write operations.- Returns:
- the number of write operations
-
getReadCount
public long getReadCount()Get the number of read operations since this store was opened. For file based stores, this is the number of file read operations.- Returns:
- the number of read operations
-
getReadBytes
public long getReadBytes()Get the number of read bytes since this store was opened.- Returns:
- the number of write operations
-
isReadOnly
public boolean isReadOnly() -
getDefaultRetentionTime
public int getDefaultRetentionTime()Get the default retention time for this store in milliseconds.- Returns:
- the retention time
-
clear
public void clear() -
getFileName
Get the file name.- Returns:
- the file name
-
getMvStore
-
markUsed
protected abstract void markUsed(long pos, int length) Mark the space as in use.- Parameters:
pos- the position in byteslength- the number of bytes
-
backup
- Throws:
IOException
-
getChunks
-
getRewriteCandidates
-
isSpaceReused
public boolean isSpaceReused() -
setReuseSpace
public void setReuseSpace(boolean reuseSpace) -
store
protected final void store() -
getChunksFillRate
public int getChunksFillRate()Get the current fill rate (percentage of used space in the file). Unlike the fill rate of the store, here we only account for chunk data; the fill rate here is how much of the chunk data is live (still referenced). Young chunks are considered live.- Returns:
- the fill rate, in percent (100 is completely full)
-
getCacheSize
public int getCacheSize()Get the maximum cache size, in MB. Note that this does not include the page chunk references cache, which is 25% of the size of the page cache.- Returns:
- the cache size
-
getCacheSizeUsed
public int getCacheSizeUsed()Get the amount of memory used for caching, in MB. Note that this does not include the page chunk references cache, which is 25% of the size of the page cache.- Returns:
- the amount of memory used for caching
-
setCacheSize
public void setCacheSize(int mb) Set the read cache size in MB.- Parameters:
mb- the cache size in MB.
-
populateInfo
-
getCacheHitRatio
public int getCacheHitRatio() -
getTocCacheHitRatio
public int getTocCacheHitRatio() -
rewriteChunks
protected boolean rewriteChunks(int writeLimit, int targetFillRate) -
executeFileStoreOperation
-
accountForRemovedPage
public void accountForRemovedPage(long pos, long version, boolean pinned, int pageNo) Remove a page.- Parameters:
pos- the position of the pageversion- at which page was removedpinned- whether page is considered pinnedpageNo- sequential page number within chunk
-