Fix - Performance Optimization: Scope Resolution & Thread Safety #2330
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.
Performance Optimization: Scope Resolution & Thread Safety
This PR introduces two major performance improvements to Koin's core resolution engine:
Problem: Original implementation synchronized every instance access, causing lock contention even for already-created instances.
Solution: Implement lock-free fast path with double-checked locking:
// Fast path: check without locking
val existing = values[context.scope.id]
if (existing != null) return existing
// Slow path: create with locking
return synchronized(this) {
values[context.scope.id] ?: create(context)
}
Changes:
Problem: Multiple sequential lookups with poor cache locality and unnecessary iterations.
Solution: Consolidated resolution logic in single method:
Key improvements:
Performance Results
Impact
Modified Files
Thread Safety
✅ Double-checked locking with @volatile ensures memory visibility
✅ Synchronized blocks prevent race conditions
✅ Uses safeHashMap (ConcurrentHashMap) for scope values
Breaking Changes: None (internal optimization only)
Fixes: #1990