Determine when the Android GC runs

2019-03-31 05:49发布

问题:

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.

回答1:

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.



回答2:

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?