Skip to content

Commit 6960d96

Browse files
tkvangordersambsnyd
authored andcommitted
Prevent duplicate creation of the rocksdb instance.
1 parent 71e6254 commit 6960d96

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

rewrite-maven/src/main/java/org/openrewrite/maven/cache/RocksdbMavenPomCache.java

+23-11
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,13 @@
2222
import java.net.URI;
2323
import java.nio.charset.StandardCharsets;
2424
import java.nio.file.Files;
25+
import java.util.HashMap;
2526
import java.util.HashSet;
27+
import java.util.Map;
2628
import java.util.Optional;
2729
import java.util.Set;
2830
import java.util.concurrent.Callable;
31+
import java.util.concurrent.atomic.AtomicReference;
2932

3033
import com.fasterxml.jackson.annotation.JsonAutoDetect;
3134
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -70,10 +73,27 @@ public class RocksdbMavenPomCache implements MavenPomCache {
7073
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
7174
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
7275
.withCreatorVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY));
76+
77+
//Init the rockdb native jni library
78+
RocksDB.loadLibrary();
79+
}
80+
81+
//While the RocksDB instance is thread-safe, attempts to create two instances of the database to the same
82+
//folder will fail.
83+
private static final Map<String, RocksDB> cacheMap = new HashMap<>();
84+
static synchronized RocksDB getCache(String workspace) {
85+
return cacheMap.computeIfAbsent(workspace, k -> {
86+
final Options options = new Options();
87+
options.setCreateIfMissing(true);
88+
try {
89+
return RocksDB.open(options, k);
90+
} catch (RocksDBException exception) {
91+
throw new IllegalStateException(("Unable to create cache database." + exception.getMessage()));
92+
}
93+
});
7394
}
7495

75-
//All three caches are put into the same database, they could be separated out at some point if we find we have
76-
//a need.
96+
7797
private final RocksDB cache;
7898
private final Set<String> unresolvablePoms = new HashSet<>();
7999

@@ -90,15 +110,7 @@ public RocksdbMavenPomCache(@Nullable File workspace) {
90110
} else if (!workspace.isDirectory()) {
91111
throw new IllegalStateException("The maven cache workspace must be a directory");
92112
}
93-
94-
RocksDB.loadLibrary();
95-
final Options options = new Options();
96-
options.setCreateIfMissing(true);
97-
try {
98-
cache = RocksDB.open(options, workspace.getAbsolutePath());
99-
} catch (RocksDBException exception) {
100-
throw new IllegalStateException(("Unable to create cache database."));
101-
}
113+
cache = getCache(workspace.getAbsolutePath());
102114
fillUnresolvablePoms();
103115
}
104116

0 commit comments

Comments
 (0)