Reputation: 173
Is there any method to garbage collect an object? As I know finalize()
is called just before if any object is going to garbage collected.
Upvotes: 0
Views: 2818
Reputation: 31
You shouldn't rely on System.gc();
with images.
The following example will get the object garbage collected.
bitmap.recycle();
bitmap = null;`
Note: System.gc();
slows down the application noticeably on some devices.
Upvotes: 2
Reputation: 3508
You can check this reply which shows how to ensure GC has run at least on some fragment of the heap which uses RuntimeUtil.gc() from the jlibs:
/**
* This method guarantees that garbage collection is
* done unlike <code>{@link System#gc()}</code>
*/
public static void gc() {
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
obj = null;
while(ref.get() != null) {
System.gc();
}
}
You can use a similar technique to replace obj with a reference to the object you want to gc.
Note: The method will be stuck in an infinite loop if the GC never runs and collects the newly allocated object.
Upvotes: 1
Reputation: 115328
The only real way to politely as the garbage collector to remove the object is to remove all references that can be used to access it.
Object o = new Object();
o = null; // at this point GC may remove the object.
To force the process you can try to call System.gc()
. But remember that it does not guarantee that your object will be really deleted at this iteration of GC.
Upvotes: 6
Reputation: 718798
Is there any method to garbage collect an object?
No there isn't.
An object will (potentially) be garbage collected after becomes "unreachable". It may be possible to cause the garbage collector to be run at a specific time by calling System.gc()
. However. the JVM is allowed to ignore your System.gc()
call, and running the GC at the wrong time is a waste of resources.
Indeed, calling System.gc()
to reclaim a single object is horribly inefficient, and won't necessarily reclaim it anyway ... even if it is garbage at that point.
It is a mistake for a Java application to depend on objects being garbage collected at a particular time, or on finalizers being run at a particular time. If your application is designed to work that way, you should redesign it.
Upvotes: 4
Reputation: 47373
There is a method System.gc();
which just gives a hint to the garbage collector to garbage objects. But no, there is no method which you call and immediately an object is garbage collected.
Upvotes: 3