Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does "object" in kotlin get garbage collected

If we have an Object like this

object Repo { var activeMovies: ArrayList<Movie>? = null }

and then we call it like this to assign a value

Repo.activeMovies = movieList

after the Activity that instantiated it is finish, does it get Garbage Collected?

I know this may be very basic question but I cannot understand the lifecycle if the object type in Kotlin.

like image 461
FantomasMex Avatar asked Jan 05 '19 14:01

FantomasMex


People also ask

Does Kotlin use garbage collection?

Kotlin is run in JVM so it uses the same garbage collector as Java or any other JVM based language.

Are objects garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.

Which object is eligible for garbage collection?

When an object created in Java program is no longer reachable or used it is eligible for garbage collection.

Is Objective C garbage collected?

Objective C for the iPhone is not garbage collected, but uses retain counting memory management.


1 Answers

If we create an object like this:

object Test {
    // some functions and properties
}

and decompile it to Java, we will see next code:

public final class Test {
    public static final Test INSTANCE;

   static {
      Test var0 = new Test();
      INSTANCE = var0;
   }
}

From the decompiled code, we can see that object creates a Singleton. The initialization happens on a static block. In Java, static blocks are executed on class loading time. The instance of Test class is created at the moment when the classloader loads the class. This approach guarantees lazy-loading and thread-safety. An instance of a singleton object is kept in a static field inside the class of that object. Therefore it isn’t eligible to the garbage collection. The Test is a Singleton, whose lifespan is as long as the lifespan of an app.

Here are some useful information about static variables Android static object lifecycle and static variable null when returning to the app.

like image 195
Sergey Avatar answered Sep 20 '22 17:09

Sergey