Fix concurrency issue for Single definitions #914
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.
The bug
We were having some crashes in our production app when injecting a Segment SDK (analytics tracker). This SDK has the particularity that only one instance can be created with the same tag. (Source for reference)
We are constructing this SDK inside a Koin's
single
definition. In theory,single
only creates one instance of the bean, even in multi-threaded environments. But in our millions of daily sessions we get a few hundred crashes where this assumption fails.We managed to reproduce the issue consistently in a unit test by simulating concurrent injections a few thousands of times. 🤯
I'm submitting in the PR the most simple version of the test that I could write (our initial test was way more complicated 😂 ). The number of repetitions and threads come from trial and error, with lower numbers the test would sometime give a false positive. I'm not sure if you want to keep the test, or if this is the right place to put it. Let me know.
The cause
After some research, I came to the conclusion that the issue lies in the concurrency code from
SingleInstanceFactory
.The synchronization code in the
create()
function works fine, but there's one little operation that happens outside thesynchronized
block: thevalue =
assignment.The bug is so hard to reproduce because the affected code is such a tiny part!
The fix
I surrounded the code in
get()
with anothersynchronized
, and that seems to fix the issue. 🎉I'm no concurrency expert myself, but I can't think of any problems with this solution.