2

I have a simple app that uses a player as a Singleton.

@JvmStatic
fun getInstance(context: Context): MyPlayer {
    return INSTANCE ?: synchronized(this) {
        MyPlayer(context).also {
            INSTANCE = it
        }
    }
}

In Activity A I assign a local field to a player instance using

val player = MyPlayer.getInstance(appContext)

In Activity B after some action, I want to release the player and null out the instance. In MyPlayer class I set:

INSTANCE = null

When I go back to Activity A, the player field still has a reference to the player and it's not null.

What am I missing here?

Note: Activity A written in Java, MyPlayer in Kotlin (if it matters)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
TareK Khoury
  • 12,721
  • 16
  • 55
  • 78
  • Does this help in any way ? https://stackoverflow.com/questions/48780003/why-and-when-to-use-jvmstatic-with-companion-objects – Sreehari Feb 08 '19 at 08:06

1 Answers1

3

In activity B you are making only variable INSTANCE null not the whole object, if you go back in activity A and check MyPlayer.INSTANCE you will get null however the object is still present in memory. Activity A's player is still referencing to the object so GC wont collect.

Roshaan Farrukh
  • 399
  • 3
  • 10
  • Since it's a Singleton, the INSTANCE and all fields will have the same reference to the same object. nulling out one of them should null the rest – TareK Khoury Feb 08 '19 at 08:13
  • Yeah they are referencing to same object, but when you are calling val player = MyPlayer.getInstance(appContext), you are saying that whatever memory address the new player object has assign it to both variable INSTANCE and also to variable player, so when you are doing INSTANCE=null you are basically only disconnecting the link between variable INSTANCE and the actual object in memory, however that object is still alive in the memory and variable player is still referenceing it. – Roshaan Farrukh Feb 08 '19 at 08:22
  • Nice, makes sense now. great explanation – TareK Khoury Feb 08 '19 at 08:30