in Android Running time Android Monitor
will Show the Memory Usage. that Panel have a initiate Garbage Collection
Button while pressing that Button Memory will reduce. my question is programmatically initiate that Garbage initiation.Before CG and
After CG
Asked
Active
Viewed 1.2k times
12

Natheem Yousuf
- 143
- 2
- 2
- 8
-
You can do it, but it has totally no sense. You will just waste CPU time on it. GC will be called on it's own once needed. You should not call it manually. – Vladyslav Matviienko Dec 22 '16 at 07:00
-
Then how to prevent from OOM ?? – Natheem Yousuf Dec 22 '16 at 07:08
-
@NatheemYousuf - OOM is almost always due to your usage of bitmaps. So, the answer is to learn to better manage your bitmap memory. [Here is my answer to that](http://stackoverflow.com/a/42519335/199364); you can find many other answers also. google "android manage bitmap memory". – ToolmakerSteve Feb 28 '17 at 22:57
-
And ... there is a good chance that running the GC manually won't prevent the OOME anyway. An OOME only happens immediately after the GC has been run ... – Stephen C Nov 19 '21 at 05:36
-
@Stephen C: This isn't a duplicate. Could you please remove your "This question already has answers here:". – Robin Davies May 09 '22 at 00:02
-
This is a better duplink. https://stackoverflow.com/questions/8177802 – Stephen C May 09 '22 at 01:20
-
And I have added a new answer there ... – Stephen C May 09 '22 at 01:31
-
GC is called before OOM is thrown. This is guaranteed. It is therefore futile to call it yourself. – user207421 May 09 '22 at 01:33
1 Answers
6
Runtime.getRuntime().gc();
This line of code does not guarantee that garbage collector will be called. But it usually is as far as I can see.
And actually you don't need it. You should ensure you have no leaks and let GC work on it's own.

Fedor
- 43,261
- 10
- 79
- 89