Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing race condition in Scope - Fixed for 3.5.0 #1643

Merged
merged 1 commit into from
Sep 4, 2023

Conversation

arnaudgiuliani
Copy link
Member

@arnaudgiuliani arnaudgiuliani commented Sep 4, 2023

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 remove KoinPlatformTools.synchronized(this).

@arnaudgiuliani
Copy link
Member Author

arnaudgiuliani commented Sep 4, 2023

following from #1561 @octa-one 👍

@arnaudgiuliani
Copy link
Member Author

Code has been tested, with fixed tests.
Benchmark run also 👍

@arnaudgiuliani arnaudgiuliani added this to the core-3.5.0 milestone Sep 4, 2023
@arnaudgiuliani arnaudgiuliani merged commit 88b3223 into 3.5.0 Sep 4, 2023
14 checks passed
@arnaudgiuliani arnaudgiuliani deleted the bugfix/parameters-race branch September 4, 2023 09:50
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.

2 participants