refactor(concurrency): improve thread management and locking in monitoring services (#137)

* refactor(concurrency): improve thread management and locking in monitoring services

* chore: remove unnecessary comments
This commit is contained in:
brios
2026-04-22 17:26:33 -04:00
committed by Zach Yale
parent aab68d55c8
commit 5bcef92b65
10 changed files with 147 additions and 38 deletions
@@ -4,6 +4,7 @@ import org.booklore.util.BookUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@@ -20,6 +21,7 @@ import java.util.Set;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate // 93+ columns; only include changed columns in UPDATE SQL
@Table(name = "book_metadata")
public class BookMetadataEntity {
@@ -3,6 +3,7 @@ package org.booklore.model.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@@ -15,6 +16,7 @@ import java.util.Set;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate
@Table(name = "comic_metadata")
public class ComicMetadataEntity {
@@ -14,6 +14,8 @@ import java.nio.file.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;
@Slf4j
@@ -31,6 +33,7 @@ public class BookdropMonitoringService {
private WatchKey watchKey;
private volatile boolean paused;
private volatile boolean disabled;
private final Lock monitorLock = new ReentrantLock();
public BookdropMonitoringService(
AppProperties appProperties,
@@ -91,34 +94,44 @@ public class BookdropMonitoringService {
log.info("Stopped bookdrop folder monitor");
}
public synchronized void pauseMonitoring() {
public void pauseMonitoring() {
if (disabled) return;
if (!paused) {
if (watchKey != null) {
watchKey.cancel();
watchKey = null;
monitorLock.lock();
try {
if (!paused) {
if (watchKey != null) {
watchKey.cancel();
watchKey = null;
}
paused = true;
log.info("Bookdrop monitoring paused.");
} else {
log.info("Bookdrop monitoring already paused.");
}
paused = true;
log.info("Bookdrop monitoring paused.");
} else {
log.info("Bookdrop monitoring already paused.");
} finally {
monitorLock.unlock();
}
}
public synchronized void resumeMonitoring() {
public void resumeMonitoring() {
if (disabled) return;
if (paused) {
try {
watchKey = bookdrop.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
paused = false;
log.info("Bookdrop monitoring resumed.");
} catch (IOException e) {
log.error("Error reregistering bookdrop folder during resume", e);
monitorLock.lock();
try {
if (paused) {
try {
watchKey = bookdrop.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
paused = false;
log.info("Bookdrop monitoring resumed.");
} catch (IOException e) {
log.error("Error reregistering bookdrop folder during resume", e);
}
} else {
log.info("Bookdrop monitoring is not paused, cannot resume.");
}
} else {
log.info("Bookdrop monitoring is not paused, cannot resume.");
} finally {
monitorLock.unlock();
}
}
@@ -71,9 +71,9 @@ public class HardcoverSyncService {
}
// Set the user's API token for this sync operation
currentApiToken.set(userSettings.getHardcoverApiKey());
try {
currentApiToken.set(userSettings.getHardcoverApiKey());
if (progressPercent == null) {
log.debug("Hardcover sync skipped: no progress to sync");
return;
@@ -14,6 +14,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -27,6 +29,7 @@ public class LibraryWatchService {
private final ConcurrentHashMap<Path, WatchEntry> watches = new ConcurrentHashMap<>();
private final Map<Long, Boolean> libraryWatchStatus = new ConcurrentHashMap<>();
private final Lock watchLock = new ReentrantLock();
private record WatchEntry(WatchKey key, long libraryId) {}
@@ -157,7 +160,7 @@ public class LibraryWatchService {
log.debug("Unregistered library {} from monitoring", libraryId);
}
public synchronized boolean registerPath(Path path, long libraryId) {
public boolean registerPath(Path path, long libraryId) {
if (!Files.exists(path)) {
log.warn("Cannot register path that does not exist: {}", path);
return false;
@@ -166,6 +169,7 @@ public class LibraryWatchService {
log.warn("Cannot register path that is not a directory: {}", path);
return false;
}
watchLock.lock();
try {
if (!watches.containsKey(path)) {
WatchKey key = path.register(watchService,
@@ -176,15 +180,22 @@ public class LibraryWatchService {
}
} catch (IOException e) {
log.error("Error registering path: {}", path, e);
} finally {
watchLock.unlock();
}
return false;
}
public synchronized void unregisterPath(Path path) {
WatchEntry entry = watches.remove(path);
if (entry != null) {
entry.key().cancel();
log.debug("Unregistered path: {}", path);
public void unregisterPath(Path path) {
watchLock.lock();
try {
WatchEntry entry = watches.remove(path);
if (entry != null) {
entry.key().cancel();
log.debug("Unregistered path: {}", path);
}
} finally {
watchLock.unlock();
}
}
@@ -58,13 +58,13 @@ public class EpubReaderService {
private static final Map<String, String> CONTENT_TYPE_MAP = createContentTypeMap();
private static final ThreadLocal<DocumentBuilder> DOCUMENT_BUILDER = ThreadLocal.withInitial(() -> {
private static DocumentBuilder createDocumentBuilder() {
try {
return SecureXmlUtils.createSecureDocumentBuilder(true);
} catch (ParserConfigurationException e) {
throw new RuntimeException("Failed to create DocumentBuilder", e);
}
});
}
private static Map<String, String> createContentTypeMap() {
Map<String, String> map = new HashMap<>(32);
@@ -652,9 +652,7 @@ public class EpubReaderService {
throw new FileNotFoundException("Entry not found: " + entryPath);
}
// Use thread-local DocumentBuilder instead of creating factory each time
DocumentBuilder builder = DOCUMENT_BUILDER.get();
builder.reset(); // Reset state for reuse
DocumentBuilder builder = createDocumentBuilder();
try (InputStream is = zipFile.getInputStream(entry)) {
return builder.parse(is);
}
@@ -15,6 +15,8 @@ import tools.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@RequiredArgsConstructor
@Service
@@ -25,13 +27,16 @@ public class DefaultSettingInitializer {
private final ObjectMapper objectMapper;
private final DefaultUserSettingsProvider settingsProvider;
private static final Set<Long> initializedUsers = Collections.newSetFromMap(new ConcurrentHashMap<>());
private static final ConcurrentHashMap<Long, Lock> userLocks = new ConcurrentHashMap<>();
@Transactional
public void ensureDefaultSettings(BookLoreUser bookLoreUser) {
if (initializedUsers.contains(bookLoreUser.getId())) {
return;
}
synchronized (("user-init-" + bookLoreUser.getId()).intern()) {
Lock lock = userLocks.computeIfAbsent(bookLoreUser.getId(), _ -> new ReentrantLock());
lock.lock();
try {
if (initializedUsers.contains(bookLoreUser.getId())) return;
BookLoreUserEntity user = userRepository.findByIdWithSettings(bookLoreUser.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
for (UserSettingKey key : settingsProvider.getAllKeys()) {
@@ -40,6 +45,9 @@ public class DefaultSettingInitializer {
patchPerBookSetting(user);
userRepository.save(user);
initializedUsers.add(bookLoreUser.getId());
} finally {
lock.unlock();
userLocks.remove(bookLoreUser.getId());
}
}
@@ -31,6 +31,9 @@ server:
min-response-size: 1024
tomcat:
relaxed-query-chars: '[,],%,{,},|'
threads:
max: 20 # Virtual threads handle concurrency; platform threads just overhead
min-spare: 4
spring:
jackson:
@@ -57,8 +60,8 @@ spring:
max-lifetime: 580000 # 9.6 minutes (avoid DB-side connection cuts)
connection-test-query: SELECT 1
connection-timeout: 30000 # 30s to acquire a connection before timeout
maximum-pool-size: 20 # Higher ceiling for virtual-thread bursts
minimum-idle: 5 # Keep warm connections ready
maximum-pool-size: 10 # Virtual threads don't need large pools
minimum-idle: 2 # Minimal warm connections; virtual threads handle bursts
idle-timeout: 300000 # 5 minutes before idle connections are closed
jpa:
open-in-view: true # true until we implement proper DTOs and service-layer data fetching
@@ -70,11 +73,16 @@ spring:
hibernate:
query:
timeout: 30 # 30s max for any HQL/JPQL query
plan_cache_max_size: 256 # Reduce from 2048 default; ~200 unique queries max
in_clause_parameter_padding: true # Pad IN params to power-of-2; fewer unique plan cache entries
jdbc:
time_zone: UTC
batch_size: 500
fetch_size: 50 # Reduce JDBC roundtrips for large result sets
order_inserts: true
order_updates: true
batch_versioned_data: true # Allow batching UPDATEs on @Version entities
default_batch_fetch_size: 16 # Global batch fetch for all lazy collections (prevents N+1)
generate_statistics: ${HIBERNATE_STATISTICS:false}
threads:
virtual: