Reduce startup cache IO contention

This commit is contained in:
kltyton
2026-07-02 05:34:51 +08:00
parent 0277a3ff09
commit b782f264cf
7 changed files with 184 additions and 41 deletions
@@ -32,6 +32,8 @@ public class Main {
try {
GlobalCache.shouldAsyncPreloadPacks = LightspeedConfig.COMMON.asyncPreloadPacks.get();
GlobalCache.shouldParallelizeResourcePackLookup = LightspeedConfig.COMMON.parallelResourceLookup.get();
GlobalCache.parallelLookupMinPacks = LightspeedConfig.COMMON.parallelLookupMinPacks.get();
GlobalCache.shouldCacheResourceExistence = LightspeedConfig.COMMON.cacheResourceExistence.get();
GlobalCache.shouldIsolateModdedResourceReloadFailures = LightspeedConfig.COMMON.isolateModdedResourceReloadFailures.get();
GlobalCache.isolatedResourceReloadListenerPatterns = LightspeedConfig.COMMON.isolatedResourceReloadListenerPatterns.get()
.stream()
+94 -18
View File
@@ -41,9 +41,11 @@ public class GlobalCache {
public static volatile boolean isEnabled = true;
public static volatile boolean shouldCacheWalkedPaths = true;
public static volatile boolean shouldCacheEmptyNamespaces = true;
public static volatile boolean shouldCacheResourceExistence = true;
public static volatile boolean shouldCacheMaterials = true;
public static volatile boolean shouldAsyncPreloadPacks = true;
public static volatile boolean shouldParallelizeResourcePackLookup = true;
public static volatile int parallelLookupMinPacks = 4;
public static volatile boolean shouldIsolateModdedResourceReloadFailures = true;
public static volatile List<String> isolatedResourceReloadListenerPatterns = List.of("*");
public static final Map<CharSequence, List<String>> SPLITTED_STRINGS_BY_SEQUENCE = Maps.newConcurrentMap();
@@ -53,11 +55,13 @@ public class GlobalCache {
public static final Map<String, Map<PackType, Set<String>>> PERSISTED_NAMESPACES_BY_MOD = Maps.newConcurrentMap();
public static final Map<String, Map<PackType, Map<String, List<String>>>> PERSISTED_RESOURCE_LISTS_BY_MOD = Maps.newConcurrentMap();
public static final int WORKER_COUNT = getWorkerCount();
public static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(WORKER_COUNT, runnable -> {
Thread thread = new Thread(runnable, "Lightspeed-" + THREAD_ID.incrementAndGet());
thread.setDaemon(true);
return thread;
});
private static final AtomicInteger CACHE_THREAD_ID = new AtomicInteger();
private static final Set<CompletableFuture<?>> BACKGROUND_CACHE_TASKS = Sets.newConcurrentHashSet();
private static final int CACHE_WORKER_COUNT = getCacheWorkerCount();
public static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(WORKER_COUNT,
runnable -> newDaemonThread(runnable, "Lightspeed-", THREAD_ID, Math.max(Thread.MIN_PRIORITY, Thread.NORM_PRIORITY - 1)));
public static final ExecutorService CACHE_EXECUTOR = Executors.newFixedThreadPool(CACHE_WORKER_COUNT,
runnable -> newDaemonThread(runnable, "Lightspeed-Cache-", CACHE_THREAD_ID, Thread.MIN_PRIORITY));
public static void add(ICache cache) {
CACHES.add(cache);
@@ -66,7 +70,6 @@ public class GlobalCache {
public static CompletableFuture<Void> loadPersistedCachesAsync() {
if (PERSISTED_CACHE_LOAD_STARTED.compareAndSet(false, true)) {
persistedCacheLoad = CompletableFuture.allOf(
loadPersistedCaches(HAS_RESOURCE_CACHE_DIR, PERSISTED_EXISTENCES_BY_MOD),
loadPersistedCaches(NAMESPACE_CACHE_DIR, PERSISTED_NAMESPACES_BY_MOD),
loadPersistedCaches(RESOURCE_LIST_CACHE_DIR, PERSISTED_RESOURCE_LISTS_BY_MOD)
).exceptionally(throwable -> {
@@ -77,6 +80,17 @@ public class GlobalCache {
return persistedCacheLoad;
}
public static <K, V> CompletableFuture<Void> loadPersistedCacheAsync(File dir, String id, Map<K, V> targetMap) {
if (id == null || id.isBlank()) {
return CompletableFuture.completedFuture(null);
}
File file = new File(dir, id + ".ser");
if (!file.isFile()) {
return CompletableFuture.completedFuture(null);
}
return executeCacheLogged("load cache file " + file.getName(), () -> targetMap.putAll(CacheUtil.load(file)));
}
public static void awaitPersistedCachesLoaded() {
try {
loadPersistedCachesAsync().get(30, TimeUnit.SECONDS);
@@ -100,11 +114,26 @@ public class GlobalCache {
}, EXECUTOR);
}
public static CompletableFuture<Void> executeCacheLogged(String taskName, Runnable task) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
if (isEnabled) {
task.run();
}
} catch (Exception e) {
LOGGER.error("Lightspeed cache task failed: {}", taskName, e);
}
}, CACHE_EXECUTOR);
BACKGROUND_CACHE_TASKS.add(future);
future.whenComplete((ignored, throwable) -> BACKGROUND_CACHE_TASKS.remove(future));
return future;
}
public static IoSupplier<InputStream> findFirstResource(List<PackResources> packs, PackType type, ResourceLocation location) {
if (packs.isEmpty()) {
return null;
}
if (packs.size() == 1 || !shouldParallelizeResourcePackLookup || packs.stream().anyMatch(pack -> !isSafeForParallelLookup(pack))) {
if (packs.size() < parallelLookupMinPacks || !shouldParallelizeResourcePackLookup || packs.stream().anyMatch(pack -> !isSafeForParallelLookup(pack))) {
return findFirstResourceSequential(packs, type, location);
}
@@ -137,14 +166,17 @@ public class GlobalCache {
public static void disablePersistAndClear() {
isEnabled = false;
awaitPersistedCachesLoaded();
awaitBackgroundCacheTasks();
List<CompletableFuture<Void>> tasks = new ArrayList<>();
CacheUtil.getCacheFiles(HAS_RESOURCE_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file)));
CacheUtil.getCacheFiles(NAMESPACE_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file)));
CacheUtil.getCacheFiles(RESOURCE_LIST_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file)));
CACHES.forEach(cache -> tasks.add(executeLogged(cache.getClass().getName(), cache::lightspeed$persistAndClearCache)));
List<CompletableFuture<Void>> deleteTasks = new ArrayList<>();
CacheUtil.getCacheFiles(HAS_RESOURCE_CACHE_DIR).forEach(file -> deleteTasks.add(deleteAsync(file)));
CacheUtil.getCacheFiles(NAMESPACE_CACHE_DIR).forEach(file -> deleteTasks.add(deleteAsync(file)));
CacheUtil.getCacheFiles(RESOURCE_LIST_CACHE_DIR).forEach(file -> deleteTasks.add(deleteAsync(file)));
CompletableFuture.allOf(deleteTasks.toArray(new CompletableFuture[0])).join();
CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
List<CompletableFuture<Void>> persistTasks = new ArrayList<>();
CACHES.forEach(cache -> persistTasks.add(runPersistTask(cache)));
CompletableFuture.allOf(persistTasks.toArray(new CompletableFuture[0])).join();
SPLITTED_STRINGS_BY_SEQUENCE.clear();
CANONICAL_PATH_PER_FILE.clear();
CACHES.clear();
@@ -161,23 +193,67 @@ public class GlobalCache {
return Math.max(2, Math.min(Runtime.getRuntime().availableProcessors(), 32));
}
private static int getCacheWorkerCount() {
int configured = Integer.getInteger("lightspeed.cacheWorkers", 1);
return Math.max(1, Math.min(configured, 4));
}
private static Thread newDaemonThread(Runnable runnable, String namePrefix, AtomicInteger id, int priority) {
Thread thread = new Thread(runnable, namePrefix + id.incrementAndGet());
thread.setDaemon(true);
thread.setPriority(priority);
return thread;
}
private static <K, V> CompletableFuture<Void> loadPersistedCaches(File dir, Map<String, Map<K, V>> targetMap) {
dir.mkdirs();
CompletableFuture<?>[] futures = CacheUtil.getCacheFiles(dir)
.map(file -> CompletableFuture.runAsync(() -> {
.map(file -> executeCacheLogged("load cache file " + file.getName(), () -> {
String id = org.apache.commons.io.FilenameUtils.getBaseName(file.getName());
targetMap.put(id, CacheUtil.load(file));
}, EXECUTOR))
targetMap.computeIfAbsent(id, ignored -> Maps.newConcurrentMap()).putAll(CacheUtil.load(file));
}))
.toArray(CompletableFuture[]::new);
return CompletableFuture.allOf(futures);
}
private static CompletableFuture<Void> deleteAsync(File file) {
return executeLogged("delete cache file " + file, () -> {
return CompletableFuture.runAsync(() -> {
if (!file.delete() && file.exists()) {
LOGGER.warn("Lightspeed could not delete old cache file {}", file);
}
});
}, CACHE_EXECUTOR);
}
private static CompletableFuture<Void> runPersistTask(ICache cache) {
return CompletableFuture.runAsync(() -> {
try {
cache.lightspeed$persistAndClearCache();
} catch (Exception e) {
LOGGER.error("Lightspeed cache persist failed: {}", cache.getClass().getName(), e);
}
}, CACHE_EXECUTOR);
}
private static void awaitBackgroundCacheTasks() {
CompletableFuture<?>[] tasks = BACKGROUND_CACHE_TASKS.toArray(new CompletableFuture[0]);
if (tasks.length == 0) {
return;
}
try {
CompletableFuture.allOf(tasks).get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.warn("Lightspeed cache task wait interrupted; persisting completed cache state", e);
} catch (ExecutionException e) {
LOGGER.warn("Lightspeed cache task failed before persist", e);
} catch (TimeoutException e) {
LOGGER.warn("Lightspeed cache tasks did not finish before title screen; persisting completed cache state");
}
}
public static void shutdownExecutors() {
EXECUTOR.shutdown();
CACHE_EXECUTOR.shutdown();
}
private static IoSupplier<InputStream> findFirstResourceSequential(List<PackResources> packs, PackType type, ResourceLocation location) {
@@ -21,6 +21,8 @@ public final class LightspeedConfig {
public static final class Common {
public final ForgeConfigSpec.BooleanValue asyncPreloadPacks;
public final ForgeConfigSpec.BooleanValue parallelResourceLookup;
public final ForgeConfigSpec.IntValue parallelLookupMinPacks;
public final ForgeConfigSpec.BooleanValue cacheResourceExistence;
public final ForgeConfigSpec.BooleanValue isolateModdedResourceReloadFailures;
public final ForgeConfigSpec.ConfigValue<List<? extends String>> isolatedResourceReloadListenerPatterns;
@@ -32,6 +34,12 @@ public final class LightspeedConfig {
parallelResourceLookup = builder
.comment("Query safe resource-pack segments concurrently while preserving vanilla priority and filter order.")
.define("parallelResourceLookup", true);
parallelLookupMinPacks = builder
.comment("Minimum safe pack segment size before Lightspeed uses parallel resource lookup. Small segments are faster sequentially.")
.defineInRange("parallelLookupMinPacks", 4, 2, 64);
cacheResourceExistence = builder
.comment("Cache per-pack resource existence checks. The persisted cache is loaded lazily so it does not block startup IO.")
.define("cacheResourceExistence", true);
builder.pop();
builder.push("compatibility");
@@ -54,7 +54,7 @@ public class TitleScreenInjector {
try {
GlobalCache.disablePersistAndClear();
} finally {
GlobalCache.EXECUTOR.shutdown();
GlobalCache.shutdownExecutors();
}
});
}
@@ -92,6 +92,10 @@ public abstract class FallbackResourceManagerMixin {
if (segment.isEmpty()) {
return null;
}
if (segment.size() < GlobalCache.parallelLookupMinPacks) {
return lightspeed$searchSafeSegmentSequential(segment, location);
}
if (segment.size() == 1) {
IndexedPack indexedPack = segment.get(0);
IoSupplier<InputStream> supplier = indexedPack.pack().getResource(this.type, location);
@@ -49,6 +49,10 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
@Unique
private Map<PackType, Map<String, List<String>>> lightspeed$relativeFilePathsByPackType;
@Unique
private Set<String> lightspeed$scheduledResourceListScans;
@Unique
private volatile boolean lightspeed$existenceCacheLoadRequested;
@Unique
@@ -119,7 +123,7 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
@Inject(method = "getRootResource", at = @At("HEAD"), cancellable = true)
public void getRootResourceHeadInjected(String[] paths, CallbackInfoReturnable<IoSupplier<InputStream>> cir) {
if (!GlobalCache.isEnabled)
if (!GlobalCache.isEnabled || !GlobalCache.shouldCacheResourceExistence)
return;
String cacheKey = Arrays.toString(paths);
@@ -136,7 +140,7 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
@Inject(method = "getRootResource", at = @At("RETURN"))
public void getRootResourceReturnInjected(String[] paths, CallbackInfoReturnable<IoSupplier<InputStream>> cir) {
if (!GlobalCache.isEnabled)
if (!GlobalCache.isEnabled || !GlobalCache.shouldCacheResourceExistence)
return;
String cacheKey = Arrays.toString(paths);
@@ -154,13 +158,14 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
FileUtil.decomposePath(path).get().ifLeft(parts -> {
try {
Path root = resolve(type.getDirectory(), namespace).toAbsolutePath();
Path requestedRoot = FileUtil.resolvePath(root, parts);
List<String> cachedPaths = lightspeed$getFilePaths(type, namespace, root);
List<String> cachedPaths = lightspeed$getCachedFilePaths(type, namespace);
if (cachedPaths == null) {
lightspeed$scheduleFilePathScan(type, namespace, root);
fallbackToVanilla[0] = true;
return;
}
Path requestedRoot = FileUtil.resolvePath(root, parts);
for (String cachedPath : cachedPaths) {
Path candidate = root.resolve(cachedPath);
if (!candidate.startsWith(requestedRoot)) {
@@ -190,7 +195,9 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
@Override
public void lightspeed$persistAndClearCache() {
if (lightspeed$modFile != null) {
CacheUtil.persist(lightspeed$getExistenceByResource(), new File(HAS_RESOURCE_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
if (GlobalCache.shouldCacheResourceExistence) {
CacheUtil.persist(lightspeed$getExistenceByResource(), new File(HAS_RESOURCE_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
}
CacheUtil.persist(lightspeed$namespaces(), new File(NAMESPACE_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
CacheUtil.persist(lightspeed$relativeFilePaths(), new File(RESOURCE_LIST_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
}
@@ -202,16 +209,15 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
@Override
public void lightspeed$setModFile(IModFile modFile) {
GlobalCache.awaitPersistedCachesLoaded();
this.lightspeed$modFile = modFile;
this.lightspeed$id = modFile.getModFileInfo().moduleName() + modFile.getModFileInfo().versionString()
+ "-" + FilenameUtils.getBaseName(modFile.getFilePath().toString()).replaceAll("[^a-zA-Z0-9.-]", "");
lightspeed$setExistenceByResource(GlobalCache.PERSISTED_EXISTENCES_BY_MOD.computeIfAbsent(
lightspeed$id, i -> Maps.newConcurrentMap()));
lightspeed$namespaces().putAll(GlobalCache.PERSISTED_NAMESPACES_BY_MOD.computeIfAbsent(
lightspeed$id, i -> Maps.newConcurrentMap()));
lightspeed$relativeFilePaths().putAll(GlobalCache.PERSISTED_RESOURCE_LISTS_BY_MOD.computeIfAbsent(
lightspeed$id, i -> Maps.newConcurrentMap()));
lightspeed$namespacesByPackType = GlobalCache.PERSISTED_NAMESPACES_BY_MOD.computeIfAbsent(
lightspeed$id, i -> Maps.newConcurrentMap());
lightspeed$relativeFilePathsByPackType = GlobalCache.PERSISTED_RESOURCE_LISTS_BY_MOD.computeIfAbsent(
lightspeed$id, i -> Maps.newConcurrentMap());
}
@Override
@@ -221,20 +227,23 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
}
for (PackType packType : PackType.values()) {
GlobalCache.executeLogged("preload namespaces " + lightspeed$id + " " + packType, () -> {
Set<String> namespaces = lightspeed$getCachedNamespaces(packType);
if (namespaces == null) {
namespaces = lightspeed$scanNamespaces(packType);
lightspeed$cacheNamespaces(packType, namespaces);
}
if (lightspeed$getCachedNamespaces(packType) == null) {
GlobalCache.executeCacheLogged("preload namespaces " + lightspeed$id + " " + packType, () -> {
if (lightspeed$getCachedNamespaces(packType) == null) {
lightspeed$cacheNamespaces(packType, lightspeed$scanNamespaces(packType));
}
});
}
for (String namespace : namespaces) {
GlobalCache.executeLogged("preload " + lightspeed$id + " " + packType + " " + namespace, () -> {
Map<String, List<String>> cachedLists = lightspeed$getRelativeFilePathsMap(packType);
for (String namespace : new ArrayList<>(cachedLists.keySet())) {
if (cachedLists.get(namespace) == null) {
GlobalCache.executeCacheLogged("preload " + lightspeed$id + " " + packType + " " + namespace, () -> {
Path root = resolve(packType.getDirectory(), namespace).toAbsolutePath();
lightspeed$getFilePaths(packType, namespace, root);
});
}
});
}
}
}
@@ -253,6 +262,7 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
@Unique
public Boolean lightspeed$exists(String resourceName) {
lightspeed$requestExistenceCacheLoad();
return lightspeed$getExistenceByResource().get(resourceName);
}
@@ -277,6 +287,40 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
return scannedPaths;
}
@Unique
public List<String> lightspeed$getCachedFilePaths(PackType packType, String resourceNamespace) {
return lightspeed$getRelativeFilePathsMap(packType).get(resourceNamespace);
}
@Unique
private void lightspeed$scheduleFilePathScan(PackType packType, String resourceNamespace, Path root) {
if (!GlobalCache.isEnabled || lightspeed$id == null) {
return;
}
String key = packType.name() + "|" + resourceNamespace;
if (!lightspeed$scheduledScans().add(key)) {
return;
}
GlobalCache.executeCacheLogged("scan resource paths " + lightspeed$id + " " + packType + " " + resourceNamespace, () -> {
if (lightspeed$getCachedFilePaths(packType, resourceNamespace) == null) {
List<String> scannedPaths = lightspeed$scanRelativeFilePaths(root);
if (scannedPaths != null) {
lightspeed$getRelativeFilePathsMap(packType).put(resourceNamespace, scannedPaths);
}
}
});
}
@Unique
private void lightspeed$requestExistenceCacheLoad() {
if (!GlobalCache.isEnabled || !GlobalCache.shouldCacheResourceExistence || lightspeed$id == null || lightspeed$existenceCacheLoadRequested) {
return;
}
lightspeed$existenceCacheLoadRequested = true;
GlobalCache.loadPersistedCacheAsync(HAS_RESOURCE_CACHE_DIR, lightspeed$id, lightspeed$getExistenceByResource());
}
@Unique
private Map<String, List<String>> lightspeed$getRelativeFilePathsMap(PackType packType) {
return lightspeed$relativeFilePaths().computeIfAbsent(packType, ignored -> Maps.newConcurrentMap());
@@ -320,6 +364,14 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
return lightspeed$relativeFilePathsByPackType;
}
@Unique
private Set<String> lightspeed$scheduledScans() {
if (lightspeed$scheduledResourceListScans == null) {
lightspeed$scheduledResourceListScans = Collections.newSetFromMap(Maps.newConcurrentMap());
}
return lightspeed$scheduledResourceListScans;
}
@Unique
private List<String> lightspeed$scanRelativeFilePaths(Path root) {
try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, (candidate, attributes) -> attributes.isRegularFile())) {
@@ -40,18 +40,19 @@ public abstract class VanillaPackResourcesMixin implements IPackResources {
return;
GlobalCache.add(this);
GlobalCache.awaitPersistedCachesLoaded();
lightspeed$versionId = SharedConstants.getCurrentVersion().getId();
lightspeed$existencePerClientResource = PERSISTED_EXISTENCES_BY_MOD.computeIfAbsent(
lightspeed$versionId + "-client", k -> Maps.newConcurrentMap());
lightspeed$existencePerServerResource = PERSISTED_EXISTENCES_BY_MOD.computeIfAbsent(
lightspeed$versionId + "-server", k -> Maps.newConcurrentMap());
GlobalCache.loadPersistedCacheAsync(HAS_RESOURCE_CACHE_DIR, lightspeed$versionId + "-client", lightspeed$existencePerClientResource);
GlobalCache.loadPersistedCacheAsync(HAS_RESOURCE_CACHE_DIR, lightspeed$versionId + "-server", lightspeed$existencePerServerResource);
}
@Inject(method = "getResource", at = @At("HEAD"), cancellable = true)
public void getResourceHeadInjected(PackType packType, ResourceLocation location, CallbackInfoReturnable<IoSupplier<InputStream>> cir) {
if (!GlobalCache.isEnabled)
if (!GlobalCache.isEnabled || !GlobalCache.shouldCacheResourceExistence)
return;
Boolean exists = lightspeed$exists(packType, location.toString());
@@ -63,7 +64,7 @@ public abstract class VanillaPackResourcesMixin implements IPackResources {
@Inject(method = "getResource", at = @At("RETURN"))
public void getResourceReturnInjected(PackType packType, ResourceLocation location, CallbackInfoReturnable<IoSupplier<InputStream>> cir) {
if (!GlobalCache.isEnabled)
if (!GlobalCache.isEnabled || !GlobalCache.shouldCacheResourceExistence)
return;
boolean actuallyExists = cir.getReturnValue() != null;