MH16
MH16

Reputation: 2356

how to ensure garbage collector working or not in android?

I am working on an android project where memory management is the major concern. I have a question regarding garbage collector role.

**Suppose i am having 3 objects hold by views which have some larger data values n those values are stored thereafter.

1) So, how and when a garbage collector will release/destroy objects. 2) and out of 3 object which object will be destroyed first and why?**

Upvotes: 0

Views: 446

Answers (4)

Kevin Yuan
Kevin Yuan

Reputation: 1028

GC is part of the Java language. I think we should consider it as reliable for most(99%+) cases.

Upvotes: 1

momo
momo

Reputation: 21343

How is easier to answer than when. Basically Garbage collector check the reference of the objects and see if it still being referenced by other objects. It check the reference path from the object to its root. If the root is not referenced by any classes, then it is eligible for garbage collection. Thus it is very important in designing the application to mentally picture where the large object is referenced and whether there is a clear path to GC from any reference point. Only when we have a clear path to GC you could be sure the GC will do their work.

Now when is a harder part as there are several algorithm for garbage collection and they all behave differently. The following Wikipedia article provide a general overview of the available algorithm. The following SO Question suggested that that Android is using Mark and Sweep algorithm. The answer of who goes first depends on which object is eligible for garbage collection given a particular algorithm.

Since we have no control over GC, to manage memory consumption in our application we should focus instead on making sure that every Activity and objects that we create (especially the larger ones) are eligible for garbage collection upon ending their life cycle (i.e making sure all of them have a clear path to GC). Setting objects to null (as you see in many articles and answers) would help towards that.

Upvotes: 3

Android Killer
Android Killer

Reputation: 18489

First of all you cannot know where GC will run and you also cannot force it using System.gc().It may or may not work.You can go for implementing finalize() method which may help you to some extent.

Upvotes: 1

jainal
jainal

Reputation: 3021

when you don't need those objects then set with null value.Garbage collector will automatically release the corresponding resources.

Upvotes: 2

Related Questions