简体   繁体   中英

Determine when the Android GC runs

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM