这是代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WeakReference<Obj> weakReference = new WeakReference<>(new Obj());
// just add some code here, gc "works"
// int i = 1;
// Log.d(TAG, "onCreate: just do something");
triggerGc();
if (weakReference.get() != null) {
Log.d(TAG, "onCreate: NOT reclaimed " + weakReference.get().toString());
} else {
Log.d(TAG, "onCreate: reclaimed");
}
}
未回收弱引用的对象!但是GC确实发生了。
D/EnvTest: triggering Gc...
I/art: Starting a blocking GC Explicit
I/art: Explicit concurrent mark sweep GC freed 330(35KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 115us total 11.164ms
D/EnvTest: Gc triggered.
D/EnvTest: onCreate: NOT reclaimed com.example.yves.envtest.MainActivity$Obj@cd043f8
如果在triggerGc()之前添加一些代码,例如日志记录或赋值,则该对象将按我们期望的方式回收。
这是triggerGc()方法
private void triggerGc() {
Log.d(TAG, "triggering Gc...");
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
Log.d(TAG, "Gc triggered.");
}
Obj在这里
static class Obj{
@Override
protected void finalize() throws Throwable {
super.finalize();
Log.d(TAG, "finalize: ");
}
}