Alif Hasnain
Alif Hasnain

Reputation: 1256

Does creating singleton inside application class cause memory leak?

I have an Authenticator class which needs a context for doing some task with SharedPreferences. I created a singleton of the class inside my custom application class so that I don't need to pass the context everytime to create an instance of my Authenticator. Is this a correct approach or it can cause memory leak or other issue?

My Application class :

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        //Plant Timber for Logging in Debug Build
        if (BuildConfig.DEBUG) {
            Timber.plant(Timber.DebugTree())
        }

        Authenticator.createInstance(this)

    }

    ...
    ....
}

On other classes I can access the singleton like this :

Authenticator.INSTANCE

Upvotes: 1

Views: 261

Answers (1)

Amin Rezaei
Amin Rezaei

Reputation: 376

When objects like Context,Activity,Application, ... that have lifecycles are stored as static or in static objects you should take care of clearing them as their lifecycle ends. If you do so, there should not be any problem with storing them. Just release the instances when the lifecycle ends.

For more clarification, Activity's lifecycle ends with onDestroy and you should override this function and release accesses to it properly. for further details you can visit android documentation for Lifecycles. For cases like app termination, all the memory used by app will be cleaned and leak won't occur thus you shouldn't get worried about accesses in Application class like saving global app context.

Upvotes: 2

Related Questions