// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base;
import androidx.annotation.VisibleForTesting;
import org.chromium.build.BuildConfig;
import org.chromium.build.annotations.CheckDiscard;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* Used to assert that clean-up logic has been run before an object is GC'ed.
*
*
Usage:
*
* class MyClassWithCleanup {
* private final mLifetimeAssert = LifetimeAssert.create(this);
*
* public void destroy() {
* // If mLifetimeAssert is GC'ed before this is called, it will throw an exception
* // with a stack trace showing the stack during LifetimeAssert.create().
* LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
* }
* }
*
*/
@CheckDiscard("Lifetime assertions aren't used when DCHECK is off.")
public class LifetimeAssert {
interface TestHook {
void onCleaned(WrappedReference ref, String msg);
}
/** Thrown for failed assertions. */
static class LifetimeAssertException extends RuntimeException {
LifetimeAssertException(String msg, Throwable causedBy) {
super(msg, causedBy);
}
}
/** For capturing where objects were created. */
private static class CreationException extends RuntimeException {
CreationException() {
super("vvv This is where object was created. vvv");
}
}
// Used only for unit test.
static TestHook sTestHook;
@VisibleForTesting final WrappedReference mWrapper;
private final Object mTarget;
@VisibleForTesting
static class WrappedReference extends PhantomReference