I was looking if there a way to force garbage collector to execute everytime I want to. After checking out these related posts, I'm pretty sure that there is NO way to do it.
When does garbage collection work in java?
How to force garbage collection in Java?
I was curious about how does android handles the scenario when user enters his/her password in the device (Because keeping password related objects in the memory can be a security issue and garbage collectors should be run immediately to clear these objects).
ChooseLockPassword.java
ConfirmLockPassword.java
Regarding these files,
ChooseLockPassword.java is executed when user is trying to save his/her password.
ConfirmLockPassword.java is executed when user confirms his/her password for example, in the process of modifying password, user has to confirm the old password once.
In both these files, the following code is present
// Force a garbage collection immediately to remove remnant of user password shards
// from memory.
System.gc();
System.runFinalization();
System.gc();
What is the significance of running System.gc()
the second time ?
Is it written once more hoping that if garbage collector didn't run the first time, it will be executed the second time or, is there more to this ?
Edit :
As per link,
Garbage collection automatically frees up the memory resources used by objects, but objects can hold other kinds of resources, such as open files and network connections. The garbage collector cannot free these resources for you, so you need to write a finalizer method for any object that needs to perform such tasks as closing files, terminating network connections, deleting temporary files, and so on.
After a finalizer is invoked, objects are not freed right away. This is because a finalizer method can resurrect an object by storing the this pointer somewhere so that the object once again has references. Thus, after finalize() is called, the garbage collector must once again determine that the object is unreferenced before it can garbage-collect it.
Even though there is no finalize()
in above mentioned classes, it may have some objects which do have it in their class definition.
Overall, I think and as mentioned by @Pshemo the mentioned code is just a fail-safe way to remove the objects properly(Assuming Garbage Collector did execute when it was called).