2

I am working in an android application an I am having some memory issues.I have a lot of private and public static variables declared in an activity.

I want to know whether when an activity id finished, these private and public object cleared(Memory) or should we make it null manually by assigning it to null in on onDestroy(). Is this correct method or please advice an alternative. Also I call the garbage collector manually in every onDestroy(). Is it correct way to call the System.gc manually?

Please help me.

Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
Arun PS
  • 4,610
  • 6
  • 41
  • 56
  • variables which u declare in an activity are for that particular activity only.no need to call garbage collector to clear their memory. – AkashG Jul 11 '12 at 05:15
  • Ok.So you are telling when the finish is called all the object in it will be cleared and the memory will be released.Right ? – Arun PS Jul 11 '12 at 05:19
  • yeah..see as i told u they are accessible for that particular activity,there's no issue if you dont destroy them.But if u want to do so than make them null on onDestroy in activity. – AkashG Jul 11 '12 at 05:26
  • Thank for reply, but when I declare a variable as public static in an activity and when I finish the same activity and that variable is still having the value that I have assigned in the finished activity. So still when I finish an activity the values assigned in it not cleared and hence the memory also. – Arun PS Jul 11 '12 at 05:32
  • make them null on onDestroy() in activity. – AkashG Jul 11 '12 at 05:33
  • So will it release the memory when we do like this. Also is it a good way to doing like this. – Arun PS Jul 11 '12 at 05:37
  • Hmm...it will release memory.Try to do it – AkashG Jul 11 '12 at 05:40
  • 1
    memory for local variables gonna release after your activity finishes, But static variable memory be there. As static scope is for app life time. You can assign null as suggested by AkashG. thats it. – AAnkit Jul 11 '12 at 05:41

2 Answers2

1

As a general rule, it is a bad idea to force garbage collection(leave it on system). If we ignore virtual memory effects, garbage collection works most efficiently when there is lots of garbage to reclaim; i.e. when the allocator has run out of immediately usable free memory. If you force the garbage collector to run at any other time it will spend more time (on average) collecting.

You can call system.gc() to implicitly garbage collection, But as Garbage collector in Java is non-deterministic. so you can not assume it will free all ur memory instantly.

Ref. link >> link

Community
  • 1
  • 1
AAnkit
  • 27,299
  • 12
  • 60
  • 71
0
  1. Whenever the object don't have any references you can declare it as null.

    1. You can verify the memory information by using dumpsys meminfo (pid) command inside adb shell

    2. If you cal manually gc it will not give you a guaranty of garbage collection

Vishwanath.M
  • 6,235
  • 11
  • 42
  • 56