views:

228

answers:

4

Does it happen automatically? How do can run it?

+7  A: 

Yes, garbage colelction happens automatically. You should not need to manually run it, nor is it recommended. The whole point of garbage collection is that it should be transparent.

Please see: Tuning Garbage Collection with the 5.0 Java[tm] Virtual Machine

[BTW, there are many questions on SO related to java garbage collection]

Mitch Wheat
+2  A: 

Yes it does. You can run System.gc() but it is not recommended. Also you still can have memory leaks

DroidIn.net
It's really not recommended to run System.gc() (to reiterate). See some discussion on SO here - http://stackoverflow.com/questions/66540/system-gc-in-java/66692
JasCav
Do I have to run that System#gc thing...or will it just happen automatically /
TIMEX
Automatically given that no one hold the reference to released object. Calling System#gc is redundant and unreliable at best
DroidIn.net
Calling `System.gc()` gives the JVM only a *hint* that it should run GC. It does not guarantee that it will actually run GC. Just write efficient code and don't worry about GC's task.
BalusC
thanks all, that helps.
TIMEX
+2  A: 

The garbage collector will automatically collect when it needs to. No need to do anything yourself unless you really have to.

nalo
+1  A: 

With the Java Virtual Machine, data (objects, arrays of primitives) is stored in the heap which is a shared region of memory that all JVM thread can access. Memory is allocated for the heap when the JVM starts (and may expand to a certain limit at runtime depending on the configuration). Whenever a new object is created, a portion of the heap is allocated to store it.

When the heap is full i.e. when no further allocations can be done (this is an over simplified version, I'm skipping details), the garbage collector is started automatically to reclaim memory space. Basically, any object which is not referenced by an active thread may be safely de-allocated.

Note that the garbage collector thread normally runs as a very low process thread but, once kicked in, it can not be suspended until the task completes.

Pascal Thivent