Stay organized with collections
Save and categorize content based on your preferences.
CloseGuard
class CloseGuard
CloseGuard is a mechanism for flagging implicit finalizer cleanup of resources that should have been cleaned up by explicit close methods (aka "explicit termination methods" in Effective Java).
A simple example:
<code>class Foo {
private final CloseGuard guard = new CloseGuard();
...
public Foo() {
...;
guard.open("cleanup");
}
public void cleanup() {
guard.close();
...;
if (Build.VERSION.SDK_INT >= 28) {
Reference.reachabilityFence(this);
}
// For full correctness in the absence of a close() call, other methods may also need
// reachabilityFence() calls.
}
protected void finalize() throws Throwable {
try {
// Note that guard could be null if the constructor threw.
if (guard != null) {
guard.warnIfOpen();
}
cleanup();
} finally {
super.finalize();
}
}
}
</code>
In usage where the resource to be explicitly cleaned up is allocated after object construction, CloseGuard protection can be deferred. For example:
<code>class Bar {
private final CloseGuard guard = new CloseGuard();
...
public Bar() {
...;
}
public void connect() {
...;
guard.open("cleanup");
}
public void cleanup() {
guard.close();
...;
if (Build.VERSION.SDK_INT >= 28) {
Reference.reachabilityFence(this);
}
// For full correctness in the absence of a close() call, other methods may also need
// reachabilityFence() calls.
}
protected void finalize() throws Throwable {
try {
// Note that guard could be null if the constructor threw.
if (guard != null) {
guard.warnIfOpen();
}
cleanup();
} finally {
super.finalize();
}
}
}
</code>
When used in a constructor, calls to
open
should occur at the end of the constructor since an exception that would cause abrupt termination of the constructor will mean that the user will not have a reference to the object to cleanup explicitly. When used in a method, the call to
open
should occur just after resource acquisition.
Summary
Public constructors |
Constructs a new CloseGuard instance.
|
Public methods |
Unit |
Marks this CloseGuard instance as closed to avoid warnings on finalization.
|
Unit |
Initializes the instance with a warning that the caller should have explicitly called the closeMethodName method instead of relying on finalization.
|
Unit |
Logs a warning if the caller did not properly cleanup by calling an explicit close method before finalization.
|
Public constructors
CloseGuard
CloseGuard()
Constructs a new CloseGuard instance. open(java.lang.String)
can be used to set up the instance to warn on failure to close.
Public methods
close
fun close(): Unit
Marks this CloseGuard instance as closed to avoid warnings on finalization.
open
fun open(closeMethodName: String): Unit
Initializes the instance with a warning that the caller should have explicitly called the closeMethodName
method instead of relying on finalization.
Parameters |
closeMethodName |
String: non-null name of explicit termination method. Printed by warnIfOpen. |
Exceptions |
java.lang.NullPointerException |
if closeMethodName is null. |
warnIfOpen
fun warnIfOpen(): Unit
Logs a warning if the caller did not properly cleanup by calling an explicit close method before finalization.
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2025-02-10 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-02-10 UTC."],[],[],null,["# CloseGuard\n\nAdded in [API level 30](https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels)\n\nCloseGuard\n==========\n\n*** ** * ** ***\n\nKotlin \\|[Java](/reference/android/util/CloseGuard \"View this page in Java\") \n\n```\nclass CloseGuard\n```\n\n|---|------------------------------|\n| [kotlin.Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html) ||\n| ↳ | [android.util.CloseGuard](#) |\n\nCloseGuard is a mechanism for flagging implicit finalizer cleanup of resources that should have been cleaned up by explicit close methods (aka \"explicit termination methods\" in Effective Java).\n\nA simple example: \n\n```kotlin\n\u003ccode\u003eclass Foo {\n \n private final CloseGuard guard = new CloseGuard();\n \n ...\n \n public Foo() {\n ...;\n guard.open(\"cleanup\");\n }\n \n public void cleanup() {\n guard.close();\n ...;\n if (Build.VERSION.SDK_INT >= 28) {\n Reference.reachabilityFence(this);\n }\n // For full correctness in the absence of a close() call, other methods may also need\n // reachabilityFence() calls.\n }\n \n protected void finalize() throws Throwable {\n try {\n // Note that guard could be null if the constructor threw.\n if (guard != null) {\n guard.warnIfOpen();\n }\n cleanup();\n } finally {\n super.finalize();\n }\n }\n }\n \u003c/code\u003e\n```\nIn usage where the resource to be explicitly cleaned up is allocated after object construction, CloseGuard protection can be deferred. For example: \n\n```kotlin\n\u003ccode\u003eclass Bar {\n \n private final CloseGuard guard = new CloseGuard();\n \n ...\n \n public Bar() {\n ...;\n }\n \n public void connect() {\n ...;\n guard.open(\"cleanup\");\n }\n \n public void cleanup() {\n guard.close();\n ...;\n if (Build.VERSION.SDK_INT >= 28) {\n Reference.reachabilityFence(this);\n }\n // For full correctness in the absence of a close() call, other methods may also need\n // reachabilityFence() calls.\n }\n \n protected void finalize() throws Throwable {\n try {\n // Note that guard could be null if the constructor threw.\n if (guard != null) {\n guard.warnIfOpen();\n }\n cleanup();\n } finally {\n super.finalize();\n }\n }\n }\n \u003c/code\u003e\n```\nWhen used in a constructor, calls to `open` should occur at the end of the constructor since an exception that would cause abrupt termination of the constructor will mean that the user will not have a reference to the object to cleanup explicitly. When used in a method, the call to `open` should occur just after resource acquisition.\n\nSummary\n-------\n\n| Public constructors ||\n|-----------------------------------------------------------------------|---|\n| [CloseGuard](#CloseGuard())`()` Constructs a new CloseGuard instance. |\n\n| Public methods ||\n|------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| [Unit](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html) | [close](#close())`()` Marks this CloseGuard instance as closed to avoid warnings on finalization. |\n| [Unit](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html) | [open](#open(kotlin.String))`(`closeMethodName:` `[String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`)` Initializes the instance with a warning that the caller should have explicitly called the `closeMethodName` method instead of relying on finalization. |\n| [Unit](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html) | [warnIfOpen](#warnIfOpen())`()` Logs a warning if the caller did not properly cleanup by calling an explicit close method before finalization. |\n\nPublic constructors\n-------------------\n\n### CloseGuard\n\nAdded in [API level 30](https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels) \n\n```\nCloseGuard()\n```\n\nConstructs a new CloseGuard instance. [open(java.lang.String)](#open(kotlin.String)) can be used to set up the instance to warn on failure to close.\n\nPublic methods\n--------------\n\n### close\n\nAdded in [API level 30](https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels) \n\n```\nfun close(): Unit\n```\n\nMarks this CloseGuard instance as closed to avoid warnings on finalization. \n\n### open\n\nAdded in [API level 30](https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels) \n\n```\nfun open(closeMethodName: String): Unit\n```\n\nInitializes the instance with a warning that the caller should have explicitly called the `closeMethodName` method instead of relying on finalization.\n\n| Parameters ||\n|-------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `closeMethodName` | [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html): non-null name of explicit termination method. Printed by warnIfOpen. |\n\n| Exceptions ||\n|----------------------------------|-----------------------------|\n| `java.lang.NullPointerException` | if closeMethodName is null. |\n\n### warnIfOpen\n\nAdded in [API level 30](https://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels) \n\n```\nfun warnIfOpen(): Unit\n```\n\nLogs a warning if the caller did not properly cleanup by calling an explicit close method before finalization."]]