Skip to content

Commit cd8ac24

Browse files
committed
block cache
1 parent a5ad1d3 commit cd8ac24

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

scorex-transaction/src/main/scala/scorex/transaction/state/database/blockchain/StoredBlockchain.scala

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import scorex.transaction.{BlockChain, TransactionModule}
1212
import scorex.utils.ScorexLogging
1313

1414
import scala.collection.JavaConversions._
15+
import scala.collection.concurrent.TrieMap
1516
import scala.util.{Failure, Success, Try}
1617

1718
/**
@@ -26,6 +27,9 @@ class StoredBlockchain(db: MVStore)
2627
val blocks: MVMap[Int, Array[Byte]] = database.openMap("blocks")
2728
val signatures: MVMap[Int, BlockId] = database.openMap("signatures")
2829
val signaturesReverse: MVMap[BlockId, Int] = database.openMap("signaturesReverse")
30+
private val BlocksCacheSizeLimit: Int = 1000
31+
private var blocksCacheSize: Int = 0
32+
private val blocksCache: TrieMap[Int, Option[Block]] = TrieMap.empty
2933

3034
//TOOD remove when no blockchains without signaturesReverse remains
3135
if (signaturesReverse.size() != signatures.size()) {
@@ -46,10 +50,19 @@ class StoredBlockchain(db: MVStore)
4650
signaturesReverse.put(block.uniqueId, height)
4751
}
4852

49-
def readBlock(height: Int): Option[Block] =
50-
Try(Option(blocks.get(height))).toOption.flatten.flatMap(b => Block.parseBytes(b).toOption)
53+
def readBlock(height: Int): Option[Block] = {
54+
if(blocksCacheSize > BlocksCacheSizeLimit) {
55+
blocksCacheSize = 0
56+
blocksCache.clear()
57+
} else {
58+
blocksCacheSize = blocksCacheSize + 1
59+
}
60+
blocksCache.getOrElseUpdate(height,
61+
Try(Option(blocks.get(height))).toOption.flatten.flatMap(b => Block.parseBytes(b).toOption))
62+
}
5163

5264
def deleteBlock(height: Int): Unit = {
65+
blocksCache.remove(height)
5366
blocks.remove(height)
5467
val vOpt = Option(signatures.remove(height))
5568
vOpt.map(v => signaturesReverse.remove(v))

0 commit comments

Comments
 (0)