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:
@@ -21,6 +21,7 @@ Thanks for your interest in contributing to Grimmory! Whether you're fixing bugs
|
||||
- [Getting Started](#getting-started)
|
||||
- [Development Setup](#development-setup)
|
||||
- [Running Tests](#running-tests)
|
||||
- [Building the Production Docker Image](#building-the-production-docker-image)
|
||||
- [Making Changes](#making-changes)
|
||||
- [Submitting a Pull Request](#submitting-a-pull-request)
|
||||
- [Backend Conventions](#backend-conventions)
|
||||
@@ -211,6 +212,66 @@ cd booklore-api
|
||||
|
||||
---
|
||||
|
||||
## Building the Production Docker Image
|
||||
|
||||
To verify your changes in an environment identical to production, build and run the full Docker image locally. The multi-stage `Dockerfile` in the project root compiles both the Angular frontend and the Spring Boot backend, so you don't need any local toolchain beyond Docker.
|
||||
|
||||
> **Note:** The first build downloads dependencies and caches them in Docker layers. Subsequent builds are significantly faster.
|
||||
|
||||
### Run
|
||||
|
||||
You need a MariaDB instance accessible to the container. The easiest way is to use the existing Docker Compose database from the dev stack, or bring your own:
|
||||
|
||||
```bash
|
||||
|
||||
# From the repository root
|
||||
docker build -t grimmory:local .
|
||||
|
||||
# Start only the database from the dev stack
|
||||
docker compose -f dev.docker-compose.yml up -d backend_db
|
||||
|
||||
# Run the production image against it, reusing the dev stack's data
|
||||
docker run --rm -it \
|
||||
--name grimmory-local \
|
||||
--network host \
|
||||
-e "SPRING_DATASOURCE_URL=jdbc:mariadb://localhost:3366/booklore?createDatabaseIfNotExist=true" \
|
||||
-e "SPRING_DATASOURCE_USERNAME=booklore" \
|
||||
-e "SPRING_DATASOURCE_PASSWORD=booklore" \
|
||||
-v ./shared/data:/app/data \
|
||||
-v ./shared/books:/books \
|
||||
-v ./shared/bookdrop:/bookdrop \
|
||||
-p 6060:6060 \
|
||||
grimmory:local
|
||||
```
|
||||
|
||||
The application will be available at http://localhost:6060.
|
||||
|
||||
### Cleanup
|
||||
|
||||
```bash
|
||||
# Stop and remove the container
|
||||
docker stop grimmory-local
|
||||
|
||||
# Stop the database service when done
|
||||
docker compose -f dev.docker-compose.yml down
|
||||
```
|
||||
|
||||
### Cross-platform build (optional)
|
||||
|
||||
If you want to test a different architecture (e.g., ARM64 on an x86 machine):
|
||||
|
||||
```bash
|
||||
docker buildx build --platform linux/arm64 -t grimmory:local-arm64 --load .
|
||||
```
|
||||
|
||||
### Tips
|
||||
|
||||
- **Memory:** The image defaults to 60% of container RAM. Limit with `--memory=512m` or similar to simulate constrained environments.
|
||||
- **Volumes:** Mount your book directories to `/books`, data/config to `/app/data`, and an optional bookdrop folder to `/bookdrop`. The example above reuses the dev stack's `shared/` folders so your existing library and covers are available.
|
||||
- **Logs:** Application logs are written to stdout. Use `docker logs -f grimmory-local` to follow them.
|
||||
|
||||
---
|
||||
|
||||
## Making Changes
|
||||
|
||||
### Branch Naming
|
||||
|
||||
+7
-1
@@ -58,7 +58,13 @@ ADD \
|
||||
FROM kepubify-layer-${TARGETARCH} AS kepubify-layer
|
||||
|
||||
FROM eclipse-temurin:25-jre-alpine
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseG1GC -XX:+UseCompactObjectHeaders -XX:+UseStringDeduplication -XX:MaxRAMPercentage=75.0 -XX:+ExitOnOutOfMemoryError"
|
||||
|
||||
ENV JAVA_TOOL_OPTIONS="-XX:+UseShenandoahGC \
|
||||
-XX:ShenandoahGCHeuristics=compact \
|
||||
-XX:+UseCompactObjectHeaders \
|
||||
-XX:MaxRAMPercentage=60.0 \
|
||||
-XX:InitialRAMPercentage=8.0 \
|
||||
-XX:+ExitOnOutOfMemoryError"
|
||||
|
||||
RUN apk add --no-cache su-exec libstdc++ libgcc && \
|
||||
mkdir -p /bookdrop
|
||||
|
||||
@@ -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 {
|
||||
|
||||
|
||||
+34
-21
@@ -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;
|
||||
|
||||
+17
-6
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user