C + + has destructor this thing, can be very good in the object before the destruction of the work of releasing external resources, but Java does not. Object.Finalize () provides a mechanism similar to a destructor, but it is unsafe, causes severe memory consumption, and degrades performance, and should be avoided. Best practice is: Like the Java class Library IO stream, database connection, socket, provide the display of the resource release interface, programmers use these resources, you must show the release. So you can forget the existence of object.finalize () . When the JVM is started, a finalizer thread is created to support the execution of the Finalize method.
For reference and reference queues, Java provides 4 types of references, which have their own unique performance in garbage collection. Referencequeue is used to work with references, and can be run without referencequeue . When creating a reference, you can specify the associated queue, and when the GC frees object memory, the reference is added to the reference queue, which is equivalent to a notification mechanism . When there is data in the associated reference queue, it means that the object in the heap memory that the reference refers to is reclaimed. In this way, the JVM allows us to do something we want to do when the object is destroyed. The JVM provides a referencehandler thread that joins the reference to the registered reference queue.
The Finalze mechanism is to execute the logic in object.finalize () , then destroy the objects in the heap, the reference and queue mechanism, destroy the object first, and then execute our own logic. You can see that using references and queue mechanisms is more efficient because garbage objects are released more quickly. If it is the destruction of the monitoring object, then the most appropriate is the phantom reference, such as Sun.misc.Cleaner is the use of phantom Reference, to monitor the destruction of objects, the use of NiO is this.
The above article on the finalize mechanism and reference, the use of reference queues is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.