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

[optimization] Avoid unnecessary locking in single and scoped instances #1990

Open
JustinBis opened this issue Sep 19, 2024 · 0 comments
Open

Comments

@JustinBis
Copy link

ScopedInstanceFactory and SingleInstanceFactory both lock on every call to get. This adds unnecessary overhead since locking is only required during the first initialization of an object.

Koin should add double-checked locking so that we can avoid locking every time we inject a single or scoped instance.

See Dagger's DoubleCheck for an example in Java that is widely employed: https://github.com/google/dagger/blob/f8a09b29683687720ae3e0e5ac241f3a4a054d6e/java/dagger/internal/DoubleCheck.java#L29

Example implementation

    // In SingleInstanceFactory
    @Volatile
    private var value: T? = null

    override fun get(context: InstanceContext): T {
        // Fast path to avoid locking if this instance is already initialized
        if (!isCreated(context)) {
            KoinPlatformTools.synchronized(this) {
                if (!isCreated(context)) {
                    value = create(context)
                }
            }
        }
        return getValue()
    }

Note that the multiplatform @Volatile is necessary for this to be correct on JVM and native platforms.

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

No branches or pull requests

1 participant