Skip to content

Commit a0ff654

Browse files
authored
feat(db): improve SnapshotRoot cache consistency (#7078)
* feat(db): improve SnapshotRoot cache consistency * test(db): cover and document SnapshotRoot cache protocol * test(db): use a named daemon executor in SnapshotRoot race test * test(db): cover SnapshotRoot write ordering and generation monotonicity
1 parent 0e4587c commit a0ff654

2 files changed

Lines changed: 874 additions & 1 deletion

File tree

‎chainbase/src/main/java/org/tron/core/db2/core/SnapshotRoot.java‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,15 @@ public class SnapshotRoot extends AbstractSnapshot<byte[], byte[]> {
3131
private static final List<String> CACHE_DBS = CommonParameter.getInstance()
3232
.getStorage().getCacheDbs();
3333

34+
// Refill protocol for the shared root cache. Writes to one root must stay serialized
35+
// (SnapshotManager runs them one at a time); readers call get() concurrently.
36+
// - get() captures cacheGen before db.get and refills only if cacheGen is unchanged.
37+
// - A writer completes the db write, then advances cacheGen under cacheLock, then publishes
38+
// the cache entries.
39+
// - The refill rechecks cacheGen and writes the cache while holding the same cacheLock.
40+
private final Object cacheLock = new Object();
41+
private volatile long cacheGen = 0L;
42+
3443
public SnapshotRoot(DB<byte[], byte[]> db) {
3544
this.db = db;
3645
solidity = this;
@@ -52,8 +61,9 @@ public byte[] get(byte[] key) {
5261
if (cache != null) {
5362
return cache.getBytes();
5463
}
64+
long observed = this.cacheGen;
5565
byte[] value = db.get(key);
56-
putCache(key, value);
66+
refillCache(key, value, observed);
5767
return value;
5868
}
5969

@@ -153,16 +163,32 @@ private boolean cached() {
153163

154164
private void putCache(byte[] key, byte[] value) {
155165
if (cached()) {
166+
synchronized (this.cacheLock) {
167+
this.cacheGen++;
168+
}
156169
cache.put(WrappedByteArray.of(key), WrappedByteArray.of(value));
157170
}
158171
}
159172

160173
private void putCache(Map<WrappedByteArray, WrappedByteArray> values) {
161174
if (cached()) {
175+
synchronized (this.cacheLock) {
176+
this.cacheGen++;
177+
}
162178
values.forEach(cache::put);
163179
}
164180
}
165181

182+
private void refillCache(byte[] key, byte[] value, long observed) {
183+
if (cached() && this.cacheGen == observed) {
184+
synchronized (this.cacheLock) {
185+
if (this.cacheGen == observed) {
186+
cache.put(WrappedByteArray.of(key), WrappedByteArray.of(value));
187+
}
188+
}
189+
}
190+
}
191+
166192
private WrappedByteArray getCache(byte[] key) {
167193
if (cached()) {
168194
return cache.getIfPresent(WrappedByteArray.of(key));

0 commit comments

Comments
 (0)