A
A
alekseyHunter2019-08-31 09:41:45
Android
alekseyHunter, 2019-08-31 09:41:45

How does the garbage collector work with objects?

I'm interested in the features of memory cleaning by the garbage collector, namely how it behaves with objects passed to functions.
Example #1.1 :

val ft = supportFragmentManager.beginTransaction()
var fragment = ListObjectsFragment()
ft.replace(R.id.fragment_container, fragment, LIST_OBJECTS_FRAGMENT)
ft.commit()

The object will not be marked by the garbage collector while it has a reference, which, in turn, will exist until the end of the method.
Example #1.2 :
val ft = supportFragmentManager.beginTransaction()
var fragment: Fragment?
fragment = ListObjectsFragment()
ft.replace(R.id.fragment_container, fragment, LIST_OBJECTS_FRAGMENT)
ft.commit()
fragment = null

The object will be garbage collected after the commit.
Example #2 :
val ft = supportFragmentManager.beginTransaction()
ft.replace(R.id.fragment_container, ListObjectsFragment(), LIST_OBJECTS_FRAGMENT)
ft.commit()

The object will be garbage collected immediately because it is not referenced.
You can call the garbage collector yourself, but then the application may hang for a couple of seconds, or you can wait for a call from the system. It turns out that there is no difference in the declaration of the object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-08-31
@alekseyHunter

Reasoning is wrong. Read FragmentManager code. In none of the cases will the object be marked, deleted, etc. The link to it will remain in the transaction.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question