2

Possible Duplicate:
Java garbage collection

I know that we have to free object in C, C++ after processing finish to get back the memory. However, I don't know how to free object in java and android. Is that enough for just assign null to the object?

Community
  • 1
  • 1
barssala
  • 463
  • 2
  • 6
  • 22

5 Answers5

4

In Java it is un-necessary to free objects.

Java has a built in Garbage Collector which runs when ever it needs to and clear out all resources that are no longer in use in order to free memory. A java developer may make a call to the java runtime to run the Garbage Collecter using System.gc(); however this is just a suggestion to the runtime and may not always result in it being run.

In cases where you are using readers and images, be sure to call .recycle() and .close() where applicable.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
4

A simple java object especially (E.g. model objects) can be freed by garbage collector IF other objects has no reference to it.

If I were you, don't trust too much that garbage collector because there are some objects that you must free, one of them is the Bitmap objects

Bitmaps eat more RAM in your android app.

Bitmap b = createLargeBitmap();
Bitmap b2 = b;

If you remove all references to that object and let garbage collector kill it

b = null;
b2 = null;

you might get a memory leak or OutOfMemory error.

So you need to call recycle() to fully freed the bitmap.

b.recycle();
b = null;
b2 = null;

// Sorry for my wrong grammar :)

2

In most cases, setting a var to null is enough. A better answer to answer your questions is how to leak the memory which details explained in this post .

Community
  • 1
  • 1
wtsang02
  • 18,603
  • 10
  • 49
  • 67
1

Memory deallocation is automatically done by Java garbage collector . You can't force garbage collector to free memory through your code.

Calling System.gc() doesnot guarantee garbage collector to RUN and FREE memory , final decision is taken by Java runtime.

Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
0

Android (which uses Java language) is a garbage-collected environment, meaning the virtual machine will automatically remove objects which no longer have any references.

Hence the question you should be asking is: how do you ensure your program does not use too much memory. This is normally achieved by ensuring you don't put too many objects in your in-memory data structure, persist your information into file system etc.

gerrytan
  • 40,313
  • 9
  • 84
  • 99