Fixing race condition in Scope - Fixed for 3.5.0 #1643
Merged
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.
Original PR from @octa-one
A race condition may occur when using the same Scope from different threads.
Now only add and remove calls are synchronized. And operations between these calls can be in a race.
Imagine that 2 threads are simultaneously resolving instances from some scope. These instances need parameters to be created. This means that some of their dependencies will be found in
_parameterStack
.We call the
resolveInstance
method simultaneously from both threads.The first thread puts the parameters on the
_parameterStack
. The second thread does the same. Next, the first thread calls_parameterStack.firstOrNull()
and gets parameters from the second thread.It turns out that the threads swapped their parameters.
This could be solved by additional synchronization, but in fact the threads don't need to be synchronized here. Resolution of particular dependencies takes place on a single thread, the main thing is to make sure that the stack is not changed from the outside during the resolution.
ThreadLocal is suitable for this purpose.
And since we made
_parameterStack
thread local, we don't need to additionally synchronize access to it and can removeKoinPlatformTools.synchronized(this)
.