Optimize addMonitoredItem with O(1) lookup and fix concurrency #1676
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What problem(s) was I solving?
The
addMonitoredItemmethod inOpcUaSubscriptionhad two performance and correctness issues:O(n) lookup: Used
monitoredItems.containsValue(item)which scans the entire map on every call. For subscriptions with thousands of monitored items, this becomes a significant bottleneck.Thread safety: The
itemsToDeletecollection was anArrayListwhich is not thread-safe and has O(n) removal complexity.What user-facing changes did I ship?
No API changes. This is a performance optimization that improves scalability for subscriptions with large numbers of monitored items.
How I implemented it
Changed
itemsToDeletedata structure: ReplacedArrayList<OpcUaMonitoredItem>with aSetbacked byConcurrentHashMapviaCollections.newSetFromMap(). This provides:Rewrote
addMonitoredItemlogic: Instead of scanning the map values, the method now:The new implementation explicitly handles three cases:
How to verify it
Manual Testing
Description for the changelog
Improved
OpcUaSubscription.addMonitoredItemperformance from O(n) to O(1) by using direct map lookup instead of value scanning, and made the pending deletion collection thread-safe.