fix RocksDBUtil bugs

This commit is contained in:
CaiHQ 2021-11-02 00:30:32 +08:00
parent 3c92f29d63
commit 32c882ec07

View File

@ -12,6 +12,8 @@ import wrp.jdk.nashorn.internal.runtime.ScriptObject;
import wrp.jdk.nashorn.internal.scripts.JO; import wrp.jdk.nashorn.internal.scripts.JO;
import java.io.File; import java.io.File;
import java.util.HashMap;
import java.util.Map;
@PermissionStub(permission = Permission.RocksDB) @PermissionStub(permission = Permission.RocksDB)
public class RocksDBUtil { public class RocksDBUtil {
@ -19,32 +21,45 @@ public class RocksDBUtil {
RocksDB.loadLibrary(); RocksDB.loadLibrary();
} }
static Map<String, RocksDBUtil> cacheDB = new HashMap<>();
RocksDB rocksDB; RocksDB rocksDB;
String path;
public RocksDBUtil(String path, boolean readOnly) { public RocksDBUtil(String path, boolean readOnly) {
try { try {
this.path = path;
Options options = new Options(); Options options = new Options();
options.setCreateIfMissing(true); options.setCreateIfMissing(true);
File parent = new File("./ContractDB/" + ContractProcess.instance.getContractName()); File parent = new File("./ContractDB/" + ContractProcess.instance.getContractName());
path = new File(parent, path).getAbsolutePath(); File dir = new File(parent, path);
File lockFile = new File(path, "LOCK"); if (!dir.exists()) dir.mkdirs();
File lockFile = new File(dir, "LOCK");
lockFile.delete(); lockFile.delete();
if (readOnly) { if (readOnly) {
rocksDB = RocksDB.openReadOnly(options, path); rocksDB = RocksDB.openReadOnly(options, path);
} else { } else {
rocksDB = RocksDB.open(options, path); rocksDB = RocksDB.open(options, path);
} }
} catch (RocksDBException e) { } catch (RocksDBException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public static RocksDBUtil loadDB(String path, boolean readOnly) { public static RocksDBUtil loadDB(String path, boolean readOnly) {
return new RocksDBUtil(path, readOnly); if (cacheDB.containsKey(path)) return cacheDB.get(path);
RocksDBUtil ret = new RocksDBUtil(path, readOnly);
cacheDB.put(path, ret);
return ret;
} }
public static RocksDBUtil loadDB(String path, String readOnly) { public static RocksDBUtil loadDB(String path, String readOnly) {
return new RocksDBUtil(path, Boolean.parseBoolean(readOnly)); return loadDB(path, Boolean.parseBoolean(readOnly));
}
public void close() {
rocksDB.close();
cacheDB.remove(path);
} }
public String get(String key) { public String get(String key) {