|
| 1 | +package org.tron.core.db2.common; |
| 2 | + |
| 3 | +import java.lang.reflect.Array; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Iterator; |
| 7 | +import java.util.LinkedHashMap; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.stream.Collectors; |
| 11 | +import org.tron.core.db.KhaosDatabase.KhaosBlock; |
| 12 | + |
| 13 | +public class TxCacheDB implements DB<Key, Long> { |
| 14 | + private final int BLOCK_COUNT = 65_536; |
| 15 | + private Map<Key, Long> db = new HashMap<>(); |
| 16 | + private Map<Long, ArrayList<Key>> blockNumMap = new LinkedHashMap<Long, ArrayList<Key>>() { |
| 17 | + @Override |
| 18 | + protected boolean removeEldestEntry(Map.Entry<Long, ArrayList<Key>> entry) { |
| 19 | + long blockNum = entry.getKey(); |
| 20 | + List<Key> txs = entry.getValue(); |
| 21 | + txs.forEach(db::remove); |
| 22 | + if (blockNumMap.size() > BLOCK_COUNT) { |
| 23 | + blockNumMap.remove(blockNum); |
| 24 | + } |
| 25 | + return false; |
| 26 | + } |
| 27 | + }; |
| 28 | + |
| 29 | + @Override |
| 30 | + public Long get(Key key) { |
| 31 | + return db.get(key); |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public void put(Key key, Long value) { |
| 36 | + blockNumMap.computeIfAbsent(value, listBlk -> new ArrayList<>()).add(key); |
| 37 | + db.put(key, value); |
| 38 | + } |
| 39 | + |
| 40 | + @Override |
| 41 | + public long size() { |
| 42 | + return db.size(); |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public boolean isEmpty() { |
| 47 | + return db.isEmpty(); |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public void remove(Key key) { |
| 52 | + db.remove(key); |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public Iterator<Map.Entry<Key,Long>> iterator() { |
| 57 | + return db.entrySet().iterator(); |
| 58 | + } |
| 59 | +} |
0 commit comments