1 // Copyright 2021 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.lifetime; 6 7 /** 8 * Utility class that help ensure destruction of objects happens only once. 9 * 10 * This class does not guarantee thread safety. When thread safety is desired, please use 11 * {@see org.chromium.base.ThreadUtils.ThreadChecker}. 12 * 13 * To use: 14 * 1. In constructor of an instance a DestroyChecker field should be initialized with a new 15 * DestroyChecker. 16 * 2. All of the methods that need to ensure that the object is used safely, should call 17 * {@link #checkNotDestroyed()} to make sure that DestroyChecker hasn't been destroyed. 18 * 3. When the guarded object is destroyed, it should be enough to call {@link #destroy()} on the 19 * DestroyChecker. That operation is not idempotent, and it asserts the state of the checker. 20 * It is therefore not necessary to call {@link #checkNotDestroyed()} in that case. It is also 21 * not allowed to call {@link #destroy()} more than once. 22 */ 23 public class DestroyChecker implements Destroyable { 24 private boolean mIsDestroyed; 25 26 @Override destroy()27 public void destroy() { 28 checkNotDestroyed(); 29 mIsDestroyed = true; 30 } 31 32 /** Returns whether the checker is already destroyed. */ isDestroyed()33 public boolean isDestroyed() { 34 return mIsDestroyed; 35 } 36 37 /** Checks whether the object is already destroyed and asserts if it is. */ checkNotDestroyed()38 public void checkNotDestroyed() { 39 assert !mIsDestroyed : "Object is already destroyed."; 40 } 41 } 42