Java Cleaner Class
java.lang.ref.Cleaner is a utility introduced in Java 9 for managing object cleanup, providing a safe way to clean up resources during garbage collection. It can replace finalize method, releasing external resources by performing cleanup operations when the object is no longer in use, and it is more efficient and reliable than finalize is more efficient and reliable.
1. Cleaner The Role of
Cleaner allows us to register a cleanup action that is automatically executed when the object becomes unreachable (i.e., about to be garbage collected). Typical application scenarios include:
- Automatically release non-Java memory resources, such as closing files, database connections, socket connections, etc.
- Replacing
finalize, to achieve automatic resource release, avoiding resource leaks caused by forgetting to callclose()method.
2. Cleaner Basic usage of
The following are Cleaner The basic usage of
- creation
CleanerExample:Cleaner.create(). - Create an object that needs cleanup and register it with a cleanup action to
Cleanermiddle. When the object is no longer referenced, the cleanup action is automatically executed.
3. Usage Example
The following example shows how to use Cleaner to create a resource that needs cleanup and automatically perform the cleanup operation when the object becomes unreachable:
Example
import
java.lang.ref.Cleaner
;
public
class
CleanerExample
{
// Create a Cleaner instance
private
static
final
Cleaner cleaner
=
Cleaner.
create
(
)
;
// Define a resource that needs cleanup
static
class
Resource
implements
AutoCloseable
{
// Cleanup task - used to release resources
private
final
Cleaner.
Cleanable
cleanable
;
Resource
(
)
{
// Register the cleanup task, executed when the Resource instance becomes unreachable
this
.
cleanable
=
cleaner.
register
(
this
,
new
ResourceCleaner
(
)
)
;
System
.
out
.
println
(
"Resource initialized"
)
;
}
// Clean up resources
private
static
class
ResourceCleaner
implements
Runnable
{
@Override
public
void
run
(
)
{
System
.
out
.
println
(
"Cleaning up resource..."
)
;
}
}
@Override
public
void
close
(
)
{
// Actively release resources, cancel the cleanup task registered with Cleaner
cleanable.
clean
(
)
;
System
.
out
.
println
(
"Resource closed"
)
;
}
}
public
static
void
main
(
String
[
]
args
)
{
// Use the resource
try
(
Resource resource
=
new
Resource
(
)
)
{
System
.
out
.
println
(
"Using resource..."
)
;
}
// close() is called automatically, manually clean up resources
// If close() is not called, GC will execute the cleanup task
new
Resource
(
)
;
// Do not call close(), wait for GC to trigger cleanup
System
.
gc
(
)
;
// Suggest GC to run (cannot guarantee immediate cleanup)
}
}
4. Code Explanation
- Cleaner instance:
Cleaner.create()Created aCleanerinstance, used to register resources that need cleanup. - Register cleanup task: In
ResourceIn the class, callcleaner.register(this, new ResourceCleaner())to register the current object toCleaner, specifying the cleanup taskResourceCleaner. - Automatic cleanup: When
ResourceWhen the instance has no other strong references and is about to be garbage collected,Cleanerwill automatically callResourceCleaner.run(), outputting "Cleaning up resource...". - Manual cleanup: Through
close()method actively callscleanable.clean(), immediately cleaning up resources, and cancelingCleaner's task.
5. Features and Advantages of Cleaner
- High efficiency:
CleanerManaged by the JVM, avoiding thefinalize's inefficient performance issues. - Avoid finalize delay:
CleanerThe registered task can be executed promptly after the object becomes unreachable, rather than waiting for the garbage collector's delayed call. - Controllability:
CleanerAllows actively callingclean()to clean up resources, and automatically cancels the task after cleanup, avoiding repeated cleanup. - Memory and Resource Safety: Reduces the risk of manual resource management and ensures the correct release of system resources.
6. Use Cases for Cleaner
Cleaner Suitable for managing resources that need automatic release, especially when try-with-resources cannot be used. The following are typical application scenarios:
- Native resources: Used to manage off-heap memory resources, such as
DirectByteBuffer, JNI, or other native resources. - Cache cleanup: When an object is garbage collected, automatically clean up related cache data.
- Non-blocking resource cleanup: Used for non-blocking resource cleanup tasks, such as notifying other service objects that they have been collected.
7. Notes
- Use in moderation:
CleanerMainly used in special scenarios, such as ensuring leak-free non-Java resources. For simple resource management,try-with-resourcesis more suitable. - Uncontrollable execution time: Although
Cleaner's cleanup task is morefinalizetimely than, the exact execution time of the cleanup task still depends on garbage collection timing, and it is not suitable for resource management with strict timeliness requirements. - Use caution with resource-intensive cleanup tasks: Avoid performing
Cleaneroverly complex or long-running operations in, to avoid affecting garbage collection performance.
Overall,java.lang.ref.Cleaner is the recommended resource cleanup tool in Java, providing an efficient and reliable resource management approach.