views:

310

answers:

2

Does anyone know if there is a way to identify (in code, not LogCat) when the GC has run? Perhaps an intent is fired? I could analyze the LogCat output, but it would be ideal if I could determine when the GC has run from my code.

A: 

The garbage collector won't run until all of your threads are suspended. Since phones are pretty low memory environments, it's probably safe to assume that the GC is going to run after you receive an onPause() or onStop().

I don't think the GC would have a hook to tell you what it's doing though. You would probably have to allocate memory to be told that a collection happened.

I'm curious, if your program had this information, what would it do with it?

Seth
+6  A: 

You can do this with a weak reference trick:

WeakReference<GcWatcher> mGcWatcher
        = new WeakReference<GcWatcher>(new GcWatcher());
long mLastGcTime;

class GcWatcher {
    @Override
    protected void finalize() throws Throwable {
        handleGc();
        mLastGcTime = SystemClock.uptimeMillis();
        mGcWatcher = new WeakReference<GcWatcher>(new GcWatcher());
    }
}

Now... whether it is really correct for an application to do this, is another thing. :) The only place I know of anywhere we have done this in Android is the code here, and its sole purpose is to help us be smart about when we ask processes to explicitly GC such as when they go into the background.

hackbod
Thanks that looks like what I want, I think I'm missing something though, what class (interface) does GcWatcher extend (implement)?
Chris Thompson
Ah nevermind, I think I understand. Alas, I fall into the category of people that don't understand WeakReferences :) I think I understand how this works.
Chris Thompson