Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix slow desktop startup with large temp folders (#8833)

Anthony Stirling2ab6362d25b2
diff --git a/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java b/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java
index 428a1866d1..2048e2e3c8 100644
--- a/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java
+++ b/app/common/src/main/java/stirling/software/common/service/TempFileCleanupService.java
@@ -1,18 +1,9 @@
package stirling.software.common.service;
import java.io.IOException;
-import java.io.UncheckedIOException;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
import java.nio.file.Files;
-import java.nio.file.InvalidPathException;
-import java.nio.file.LinkOption;
import java.nio.file.Path;
-import java.nio.file.StandardOpenOption;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -56,15 +47,7 @@ public class TempFileCleanupService {
// Maximum recursion depth for directory traversal
private static final int MAX_RECURSION_DEPTH = 5;
- // A JPDFium dir younger than this may belong to a JVM that is still starting
- private static final long JPDFIUM_DIR_GRACE_MILLIS = 60 * 60 * 1000;
-
- // Names of the jpdfium bridge library across platforms; every extraction dir holds one
- private static final Set<String> JPDFIUM_BRIDGE_FILES =
- Set.of("jpdfium.dll", "libjpdfium.dylib", "libjpdfium.so");
-
- // Held by the owning JVM for its lifetime in fallback extraction dirs
- private static final String JPDFIUM_LOCK_FILE = ".lock";
+ // JPDFium sweeps its own extraction dirs on native load
private static final String JPDFIUM_DIR_PREFIX = "jpdfium-";
// File patterns that identify our temp files
@@ -206,7 +189,6 @@ public class TempFileCleanupService {
long maxAgeMillis = containerMode ? 0 : 24 * 60 * 60 * 1000; // 0 or 24 hours
int totalDeletedCount = cleanupUnregisteredFiles(containerMode, false, maxAgeMillis);
- totalDeletedCount += cleanupStaleJpdfiumDirs();
if (totalDeletedCount > 0) {
log.info(
"Startup cleanup complete. Deleted {} temporary files/directories",
@@ -214,116 +196,6 @@ public class TempFileCleanupService {
}
}
- /**
- * Removes JPDFium extraction dirs leaked by older versions on Windows. The age gate keeps a dir
- * whose JVM may still be extracting, the content check keeps the sweep away from a same-named
- * dir this application did not create, and the lock check keeps a running JVM's fallback dir:
- * JPDFium holds {@code .lock} there for its lifetime.
- *
- * @return number of directories removed
- */
- private int cleanupStaleJpdfiumDirs() {
- int deletedCount = 0;
- for (Path root : jpdfiumScanRoots()) {
- if (!Files.isDirectory(root)) continue;
- List<Path> stale;
- try (Stream<Path> entries = Files.list(root)) {
- stale =
- entries.filter(p -> Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS))
- .filter(
- p ->
- p.getFileName()
- .toString()
- .startsWith(JPDFIUM_DIR_PREFIX))
- .filter(p -> isOlderThan(p, JPDFIUM_DIR_GRACE_MILLIS))
- .filter(TempFileCleanupService::looksLikeJpdfiumExtraction)
- .filter(dir -> !isJpdfiumDirInUse(dir))
- .toList();
- } catch (IOException | UncheckedIOException e) {
- log.debug("JPDFium temp scan failed for {}: {}", root, e.getMessage());
- continue;
- }
- for (Path dir : stale) {
- try {
- GeneralUtils.deleteDirectory(dir);
- deletedCount++;
- log.debug("Removed stale JPDFium extraction dir: {}", dir);
- } catch (IOException e) {
- // Windows keeps loaded DLLs locked; a later startup retries.
- log.debug("Could not remove JPDFium dir {}: {}", dir, e.getMessage());
- }
- }
- }
- return deletedCount;
- }
-
- /**
- * JPDFium extracts into {@code java.io.tmpdir}; the configured system and base temp dirs
- * receive the dirs only when the JVM temp dir points at them, so all three are scanned and
- * deduplicated. An unusable configured path is skipped instead of aborting startup.
- */
- private Path[] jpdfiumScanRoots() {
- List<Path> roots = new ArrayList<>(3);
- addJpdfiumScanRoot(roots, System.getProperty("java.io.tmpdir"));
- ApplicationProperties.TempFileManagement tempFiles =
- applicationProperties.getSystem().getTempFileManagement();
- addJpdfiumScanRoot(roots, tempFiles.getSystemTempDir());
- addJpdfiumScanRoot(roots, tempFiles.getBaseTmpDir());
- return roots.toArray(Path[]::new);
- }
-
- private static void addJpdfiumScanRoot(List<Path> roots, String rawPath) {
- if (rawPath == null || rawPath.isBlank()) return;
- try {
- Path root = Path.of(rawPath);
- if (!roots.contains(root)) {
- roots.add(root);
- }
- } catch (InvalidPathException e) {
- log.debug("Skipping invalid temp scan root '{}': {}", rawPath, e.getMessage());
- }
- }
-
- /**
- * Every extraction dir holds the jpdfium bridge next to pdfium itself; requiring that exact
- * artifact keeps the sweep from deleting an unrelated dir that happens to share the prefix.
- */
- private static boolean looksLikeJpdfiumExtraction(Path dir) {
- try (Stream<Path> entries = Files.list(dir)) {
- return entries.map(path -> path.getFileName().toString().toLowerCase(Locale.ROOT))
- .anyMatch(JPDFIUM_BRIDGE_FILES::contains);
- } catch (IOException | UncheckedIOException e) {
- return false;
- }
- }
-
- /**
- * A fallback extraction dir holds a {@code .lock} the owning JVM keeps locked for its whole
- * lifetime; a free or absent lock means the dir is a leftover. Anything unreadable counts as in
- * use so cleanup fails closed.
- */
- private static boolean isJpdfiumDirInUse(Path dir) {
- Path lockFile = dir.resolve(JPDFIUM_LOCK_FILE);
- if (!Files.exists(lockFile, LinkOption.NOFOLLOW_LINKS)) return false;
- try (FileChannel channel =
- FileChannel.open(
- lockFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
- FileLock lock = channel.tryLock()) {
- return lock == null;
- } catch (IOException | RuntimeException e) {
- return true;
- }
- }
-
- private static boolean isOlderThan(Path path, long ageMillis) {
- try {
- return System.currentTimeMillis() - Files.getLastModifiedTime(path).toMillis()
- > ageMillis;
- } catch (IOException e) {
- return false;
- }
- }
-
/**
* Clean up unregistered temporary files across all configured temp directories.
*
@@ -476,7 +348,7 @@ public class TempFileCleanupService {
if (Files.isDirectory(path)) {
if (fileName.startsWith(JPDFIUM_DIR_PREFIX)) {
- // The lock-aware sweep owns these; unlinking a
+ // JPDFium's lock-aware sweep owns these; unlinking a
// live .lock would hide it from that sweep.
return;
}
diff --git a/app/common/src/main/java/stirling/software/common/util/YamlHelper.java b/app/common/src/main/java/stirling/software/common/util/YamlHelper.java
index aaf22a47cf..09b5971ad0 100644
--- a/app/common/src/main/java/stirling/software/common/util/YamlHelper.java
+++ b/app/common/src/main/java/stirling/software/common/util/YamlHelper.java
@@ -14,7 +14,6 @@ import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
@@ -346,12 +345,10 @@ public class YamlHelper {
if (this.updatedRootNode != null) {
return this.updatedRootNode;
}
+ // Parse once: every key lookup lands here, so reparsing made config sync O(keys x file).
Composer composer = new Composer(loadSettings, getParserImpl());
- Optional<Node> rootNodeOpt = composer.getSingleNode();
- if (rootNodeOpt.isPresent()) {
- return rootNodeOpt.get();
- }
- return null;
+ this.updatedRootNode = composer.getSingleNode().orElse(null);
+ return this.updatedRootNode;
}
/**
diff --git a/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java b/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java
index eb9516c7df..45742e5cb6 100644
--- a/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java
+++ b/app/common/src/test/java/stirling/software/common/service/TempFileCleanupServiceMoreTest.java
@@ -9,15 +9,11 @@ import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileTime;
import java.util.HashSet;
import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.junit.jupiter.api.AfterEach;
@@ -192,169 +188,6 @@ class TempFileCleanupServiceMoreTest {
}
}
- @Nested
- @DisplayName("cleanupStaleJpdfiumDirs")
- class JpdfiumDirs {
-
- @Test
- @DisplayName("removes stale extraction dirs and keeps fresh ones at startup")
- void removesStaleJpdfiumDirs() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path stale = Files.createDirectories(systemTempDir.resolve("jpdfium-old"));
- Files.writeString(stale.resolve("jpdfium.dll"), "dll");
- backdate(stale, 2L * 60 * 60 * 1000);
- Path fresh = Files.createDirectories(systemTempDir.resolve("jpdfium-fresh"));
-
- withJvmTmpDir(tempDir.resolve("jvm-tmp-a"), cleanupService::init);
-
- assertThat(Files.exists(stale)).isFalse();
- assertThat(Files.exists(fresh)).isTrue();
- }
-
- @Test
- @DisplayName("also scans the configured base temp dir")
- void scansBaseTempDir() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path stale = Files.createDirectories(customTempDir.resolve("jpdfium-old"));
- Files.writeString(stale.resolve("jpdfium.dll"), "dll");
- backdate(stale, 2L * 60 * 60 * 1000);
-
- withJvmTmpDir(tempDir.resolve("jvm-tmp-b"), cleanupService::init);
-
- assertThat(Files.exists(stale)).isFalse();
- }
-
- @Test
- @DisplayName("scans the JVM temp dir even when the configured system temp dir differs")
- void scansJvmTempDir() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path jvmTmp = tempDir.resolve("jvm-tmp");
- Path stale = Files.createDirectories(jvmTmp.resolve("jpdfium-old"));
- Files.writeString(stale.resolve("jpdfium.dll"), "dll");
- backdate(stale, 2L * 60 * 60 * 1000);
-
- withJvmTmpDir(jvmTmp, cleanupService::init);
-
- assertThat(Files.exists(stale)).isFalse();
- }
-
- @Test
- @DisplayName("keeps a prefixed dir whose content is not a JPDFium extraction")
- void keepsUnrelatedContent() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path impostor = Files.createDirectories(systemTempDir.resolve("jpdfium-notours"));
- Files.writeString(impostor.resolve("jpdfium-notes.txt"), "unrelated");
- backdate(impostor, 2L * 60 * 60 * 1000);
-
- withJvmTmpDir(tempDir.resolve("jvm-tmp-c"), cleanupService::init);
-
- assertThat(Files.exists(impostor)).isTrue();
- }
-
- @Test
- @DisplayName("recognizes the bridge artifact name of every platform")
- void recognizesBridgeNames() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path linux = Files.createDirectories(systemTempDir.resolve("jpdfium-linux"));
- Files.writeString(linux.resolve("libjpdfium.so"), "so");
- Path mac = Files.createDirectories(systemTempDir.resolve("jpdfium-mac"));
- Files.writeString(mac.resolve("libjpdfium.dylib"), "dylib");
- Path win = Files.createDirectories(systemTempDir.resolve("jpdfium-win"));
- Files.writeString(win.resolve("jpdfium.dll"), "dll");
- for (Path dir : new Path[] {linux, mac, win}) {
- backdate(dir, 2L * 60 * 60 * 1000);
- }
-
- withJvmTmpDir(tempDir.resolve("jvm-tmp-f"), cleanupService::init);
-
- assertThat(Files.exists(linux)).isFalse();
- assertThat(Files.exists(mac)).isFalse();
- assertThat(Files.exists(win)).isFalse();
- }
-
- @Test
- @DisplayName("skips an invalid configured root without aborting startup")
- void skipsInvalidConfiguredRoot() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
- when(tempFileManagement.getSystemTempDir()).thenReturn("bad\u0000root");
-
- Path stale = Files.createDirectories(customTempDir.resolve("jpdfium-old"));
- Files.writeString(stale.resolve("jpdfium.dll"), "dll");
- backdate(stale, 2L * 60 * 60 * 1000);
-
- withJvmTmpDir(tempDir.resolve("jvm-tmp-d"), cleanupService::init);
-
- assertThat(Files.exists(stale)).isFalse();
- }
-
- @Test
- @DisplayName("keeps an extraction dir whose lock is held by a running JVM")
- void keepsLockedExtractionDir() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path live = Files.createDirectories(systemTempDir.resolve("jpdfium-live"));
- Files.writeString(live.resolve("jpdfium.dll"), "dll");
- Path lockFile = live.resolve(".lock");
- Files.writeString(lockFile, "");
- backdate(live, 2L * 60 * 60 * 1000);
-
- try (FileChannel channel =
- FileChannel.open(
- lockFile, StandardOpenOption.READ, StandardOpenOption.WRITE);
- FileLock lock = channel.lock()) {
- withJvmTmpDir(tempDir.resolve("jvm-tmp-g"), cleanupService::init);
- assertThat(Files.exists(live)).isTrue();
- }
- }
-
- @Test
- @DisplayName("removes an extraction dir whose lock is free")
- void removesUnlockedExtractionDir() throws IOException {
- when(tempFileManagement.isStartupCleanup()).thenReturn(true);
- when(registry.contains(any(File.class))).thenReturn(false);
-
- Path leftover = Files.createDirectories(systemTempDir.resolve("jpdfium-left"));
- Files.writeString(leftover.resolve("jpdfium.dll"), "dll");
- Files.writeString(leftover.resolve(".lock"), "");
- backdate(leftover, 2L * 60 * 60 * 1000);
-
- withJvmTmpDir(tempDir.resolve("jvm-tmp-h"), cleanupService::init);
-
- assertThat(Files.exists(leftover)).isFalse();
- }
-
- @Test
- @DisplayName("reports how many extraction dirs it removed")
- void reportsRemovedCount() throws IOException {
- Path stale = Files.createDirectories(systemTempDir.resolve("jpdfium-old"));
- Files.writeString(stale.resolve("jpdfium.dll"), "dll");
- backdate(stale, 2L * 60 * 60 * 1000);
- AtomicInteger removed = new AtomicInteger(-1);
-
- withJvmTmpDir(
- tempDir.resolve("jvm-tmp-e"),
- () ->
- removed.set(
- (Integer)
- ReflectionTestUtils.invokeMethod(
- cleanupService, "cleanupStaleJpdfiumDirs")));
-
- assertThat(removed.get()).isEqualTo(1);
- }
- }
-
@Nested
@DisplayName("scheduledCleanup")
class ScheduledCleanup {
diff --git a/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java b/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java
index 2a3746f13a..86fb5a7465 100644
--- a/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java
+++ b/app/core/src/main/java/stirling/software/SPDF/config/ExternalAppDepConfig.java
@@ -97,10 +97,12 @@ public class ExternalAppDepConfig {
return null;
})
.toList();
+ // Python / OpenCV probes chain several processes, so overlap them with the rest.
+ Future<?> python = pool.submit(this::checkPythonAndOpenCV);
invokeAllWithTimeout(tasks, DEFAULT_TIMEOUT.plusSeconds(3));
-
- // Python / OpenCV special handling
- checkPythonAndOpenCV();
+ if (!awaitPythonCheck(python)) {
+ return;
+ }
disableCalibreUnlessConfined();
@@ -297,6 +299,19 @@ public class ExternalAppDepConfig {
}
}
+ private boolean awaitPythonCheck(Future<?> python) {
+ try {
+ python.get();
+ } catch (InterruptedException e) {
+ python.cancel(true);
+ Thread.currentThread().interrupt();
+ return false;
+ } catch (ExecutionException e) {
+ log.warn("Python/OpenCV dependency check failed", e.getCause());
+ }
+ return true;
+ }
+
private void invokeAllWithTimeout(List<Callable<Void>> tasks, Duration timeout) {
try {
List<Future<Void>> futures =
@@ -314,8 +329,9 @@ public class ExternalAppDepConfig {
private ProbeResult runAndWait(List<String> cmd, Duration timeout) {
ProcessBuilder pb = new ProcessBuilder(cmd);
+ Process p = null;
try {
- Process p = pb.start();
+ p = pb.start();
boolean finished = p.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS);
if (!finished) {
p.destroyForcibly();
@@ -326,7 +342,10 @@ public class ExternalAppDepConfig {
int ec = p.exitValue();
return new ProbeResult(ec, out, err);
} catch (IOException | InterruptedException e) {
- if (e instanceof InterruptedException) Thread.currentThread().interrupt();
+ if (e instanceof InterruptedException) {
+ p.destroyForcibly();
+ Thread.currentThread().interrupt();
+ }
return new ProbeResult(127, "", String.valueOf(e.getMessage()));
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigTest.java
index e2c6a326fb..2a22f888e4 100644
--- a/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/config/ExternalAppDepConfigTest.java
@@ -41,6 +41,19 @@ class ExternalAppDepConfigTest {
config = new ExternalAppDepConfig(endpointConfiguration, runtimePathConfig);
}
+ @Test
+ void interruptedStartupDoesNotMarkDependenciesChecked() {
+ Thread.currentThread().interrupt();
+ try {
+ config.checkDependencies();
+
+ assertTrue(Thread.currentThread().isInterrupted());
+ assertFalse(config.isDependenciesChecked());
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
@Test
void commandToGroupMappingIncludesRuntimePaths() throws Exception {
Map<String, List<String>> mapping = getCommandToGroupMapping();