Skip to content

fix: Update database service to handle better multi-threading access - #35

Merged
renvins merged 2 commits into
masterfrom
fix/database
Nov 20, 2025
Merged

renvins merged 2 commits into
masterfrom
fix/database

Conversation

@renvins

@renvins renvins commented Nov 20, 2025

Copy link
Copy Markdown
Owner

Description

This PR overhauls the DatabaseService to improve thread safety, eliminate blocking operations on hot paths, and fix potential race conditions during connection retries. It also includes performance optimizations for network requests.

Key Changes

1. Granular Thread Safety (Hybrid Approach)

  • Removed Full Synchronization: The startRetryTaskIfNeeded method is no longer fully synchronized. This prevents the metrics collection thread (or other threads) from blocking if the retry logic is busy.
  • Non-Blocking Hot Paths: The isConnected check now uses a volatile boolean, ensuring zero-overhead reads for the high-frequency metrics loop.
  • Safe Retry Logic:
    • Introduced AtomicReference<Task> and AtomicInteger to manage retry state without locking the entire object.
    • Implemented a Double-Checked Locking pattern using a granular lock on the retryTask object itself. This ensures that even if multiple threads report a failure simultaneously (race condition), only one retry task is ever scheduled.

2. Performance Optimizations

  • Cached Ping Request: The HttpRequest object for pings is now built once during load() and reused. This avoids creating garbage objects every 5 seconds during connection failures.
  • Correct URL Encoding: Applied URLEncoder.encode() to organization and bucket names in the write URL. This fixes connection errors for users with spaces or special characters in their config.

3. Logic & Stability

  • Fixed Infinite Loops: The retry logic is now robust against thread-pool concurrency issues that could previously spawn duplicate retry loops.
  • Explicit Cleanup: stopRetryTask now atomically gets-and-clears the task reference, ensuring a task is never cancelled twice or lost.

Why these changes?

Previous implementations either risked blocking the main metrics thread (using synchronized on the whole method) or allowed race conditions where multiple retry tasks could run in parallel (using only volatile). This new implementation provides the best of both worlds: lock-free reads for performance and strict safety for state changes.

@renvins
renvins merged commit 305577d into master Nov 20, 2025
1 check passed
@renvins
renvins deleted the fix/database branch February 27, 2026 17:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant