Table of Contents
Destruction of objects
finalize method
GC recycling of objects
In the finalize method, should you reassign a reference to yourself to avoid being recycled by GC?
What will happen if an infinite loop occurs in the finalze method?
If there is such an infinite loop in object creation, will it cause the object to be unable to be destroyed and cause memory overflow?
Home Java javaTutorial How to use Java object destruction and finalize methods

How to use Java object destruction and finalize methods

Apr 15, 2023 am 09:58 AM
java finalize

Destruction of objects

In C, the destructor method is used to release resources and destroy the object itself.

In Java, due to the existence of GC, we do not need to manually reclaim memory, which greatly reduces the workload and improves the security of the program. But Java does have a function similar to the destructor in C.

finalize method

Overload this method to perform some operations when the class is recycled by GC.

The following is an example of a class implementing finalize.

The Aoo class has an int and a String property, overloads toString and prints the object and its creation time in the construction, and prints the object and the calling time in finalize.

Aoo Class

public class Aoo {
       private int id;
       private String name;

       public Aoo(){
              this(0, null);
       }

       public Aoo(int id, String name){
              this.id = id;
              this.name = name;
              System.out.println(this.toString() + " now create:" + System.currentTimeMillis());
       }
        /*
        * 省略get/set/toString
        */
       protected void finalize() throws Throwable{
              super.finalize();
              System.out.println(this.toString() + "now finalize:" + System.currentTimeMillis());
       }
}
Copy after login

First, a simple test

main method

public class FinalizeTest {
       public static void main(String[] args) throws Exception {
              Aoo a = new Aoo(1, "a");
              a = null;
              System.gc()
              Thread.sleep(2000);
              System.exit(0);
       }
}
Copy after login

Print the result :

id:1 name:a now create:1497547723036
id:1 name:anow finalize:1497547724059

GC recycling of objects

Here the GC is manually called to clean up the memory, and if you comment out System.gc();, the printed result is like this:

id:1 name:a now create:1497547846923

In other words, without specifically calling the GC, the finalize method is not called at all, which means that the object is not actively recycled at all.

Contrary to imagination, GC operates in a lazy manner. That is to say, when there is no place in the memory, GC will not actively recycle objects. In order to verify this idea, I created a Threads are used to continuously consume memory and do not actively call GC.

ThreadA class

public class ThreadA implements Runnable{
       public void run() {
              List<Integer> list = new ArrayList<Integer>();
              int i = 0;
              while(true){
                     list.add(i);
                     i++;
              }
       }
}
Copy after login

main method

public class FinalizeTest {
       public static void main(String[] args) throws Exception {
              Aoo a = new Aoo(1, "a");
              a = null;
              ThreadA ta = new ThreadA();
              Thread t = new Thread(ta);
              t.start();
              Thread.sleep(2000);
              System.exit(0);
       }
}
Copy after login

Print result:

id: 1 name:a now create:1497548135268
id:1 name:anow finalize:1497548135386

Although GC was not called manually this time, the finalize method still ran, that is to say, only if The GC will only run when the memory is consumed and the GC needs to clean up the memory.

Such a finalize method is indeed unreliable. It is not even sure whether it can be called, let alone complete any specific operation. If you need to close the stream and recover resources, it is better to call a method manually, or in Resources are released uniformly in the final block.

In the finalize method, should you reassign a reference to yourself to avoid being recycled by GC?

Try to re-reference in the finalize method to prevent GC from recycling

The modified Aoo is as follows

public class Aoo {
       public static Aoo SAVE = null;
       private int id;
       private String name;

       public Aoo(){
              this(0, null);
       }

       public Aoo(int id, String name){
              this.id = id;
              this.name = name;
              System.out.println(this.toString() + " now create:" + System.currentTimeMillis());
       }  
       /*
        * 省略get/set/toString
        */
       protected void finalize() throws Throwable{
              super.finalize();
              System.out.println(this.toString() + "now finalize:" + System.currentTimeMillis());
              SAVE = this;
       }
}
Copy after login

main method

public class FinalizeTest {
       public static void main(String[] args) throws Exception {
              Aoo.SAVE = new Aoo(1, "a");
              Aoo.SAVE = null;
              System.gc();
              Thread.sleep(500);
              System.out.println(Aoo.SAVE == null? "a is dead" : "a is alive" );              
              System.exit(0);             
       }
}
Copy after login

Print result:

id:1 name:a now create:1497551409195
id:1 name:anow finalize:1497551409201
a is alive

It can be seen here that the Aoo.SAVE object is indeed "resurrected", but this operation is limited. If the same trick is repeated, the object will not be "resurrected" again.

main method

public class FinalizeTest {
       public static void main(String[] args) throws Exception {
              Aoo.SAVE = new Aoo(1, "a");
              Aoo.SAVE = null;
              System.gc();
              Thread.sleep(500);
              System.out.println(Aoo.SAVE == null? "a is dead" : "a is alive" );

              Aoo.SAVE = null;
              System.gc();
              Thread.sleep(500);
              System.out.println(Aoo.SAVE == null? "a is dead" : "a is alive" );

              System.exit(0);          
       }
}
Copy after login

Print result:

id:1 name:a now create:1497551587715
id:1 name :anow finalize:1497551587721
a is alive
a is dead

Note here that the two operations are the same, and the finalize method will only be called once by the system.

What will happen if an infinite loop occurs in the finalze method?

Aoo class

public class Aoo {
       private int id;
       private String name;

       public Aoo(){
              this(0, null);
       }

       public Aoo(int id, String name){
              this.id = id;
              this.name = name;
              System.out.println(this.toString() + " now create:" + System.currentTimeMillis());
       }
       /*
        * 省略get/set/toString
        */
       protected void finalize() throws Throwable{
              super.finalize();
              while(true){
                     System.out.println(this.toString() + "now finalize:" + System.currentTimeMillis());
                     Thread.sleep(100);
              }
       }
}
Copy after login

main method

public class FinalizeTest {
       public static void main(String[] args) throws Exception {
              Aoo a1 = new Aoo(1 , "a1");
              Aoo a2 = new Aoo(2 , "a2");
              a1 = null;
              a2 = null;
              ThreadA ta = new ThreadA();
              Thread t = new Thread(ta);
              t.start();
              Thread.sleep(5000);

              System.exit(0);
       }
}
Copy after login

Print result:

id: 1 name:a1 now create:1497552024252
id:2 name:a2 now create:1497552024252
id:1 name:a1now finalize:1497552024373
id:1 name:a1now finalize:1497552024503
id: 1 name:a1now finalize:1497552026848
id:1 name:a1now finalize:1497552028960
id:1 name:a1now finalize:1497552032363

The result is random and sometimes executed The finalize of a1 is sometimes executed by a2.

This result illustrates two points:

1. The thread priority of the finalze method is very low, and the time interval is quite uncertain and significantly greater than 100 milliseconds.

2. This infinite loop causes the finalize method of other objects to fail to execute.

If there is such an infinite loop in object creation, will it cause the object to be unable to be destroyed and cause memory overflow?

We create a large number of Aoo objects and wait for the GC to reclaim the memory by itself.

In order to visually observe the calling of the finalize method, the printing code when the Aoo object is initialized is deleted.

main method

public class FinalizeTest {
       public static void main(String[] args) throws Exception {
              int i = 1;
              while(true){
                     Aoo a = new Aoo(i , "a" + i);
                     i++;
              }
       }
}
Copy after login

Let the program execute for about two minutes, then terminate it manually and check the output

1497554225913
id:269614 name:a269614now finalize:1497554226151
id:269614 name:a269614now finalize:1497554227635
id:269614 name:a269614now finalize:1497554227735
id:269614 name:a269614now finalize:1497554227836
id:269614 name:a269614now finalize:1497554229586
id:269614 name:a269614now finalize:1497554229686
id:269614 name:a269614now finalize:1497554229951
id:269614 name:a269614now finalize:1497554230051
id:269614 name:a269614now finalize:1497554230152
id:269614 name:a269614now finalize:1497554233699
id:269614 name:a269614now finalize:1497554233800
id:269614 name:a269614now finalize:1497554233900
id:269614 name:a269614now finalize:1497554234308
id:269614 name:a269614now finalize:1497554234408
id:269614 name:a269614now finalize:1497554234508
id:269614 name:a269614now finalize:1497554235053
id:269614 name:a269614now finalize:1497554235153
id:269614 name:a269614now finalize:1497554235253
id:269614 name:a269614now finalize:1497554235823
id:269614 name:a269614now finalize:1497554235923
id:269614 name:a269614now finalize:1497554236023
id:269614 name:a269614now finalize:1497554240324
id:269614 name:a269614now finalize:1497554240424
id:269614 name:a269614now finalize:1497554240525
id:269614 name:a269614now finalize:1497554241146
id:269614 name:a269614now finalize:1497554241247
id:269614 name:a269614now finalize:1497554241347
id:269614 name:a269614now finalize:1497554241448
id:269614 name:a269614now finalize:1497554242020
id:269614 name:a269614now finalize:1497554242120
id:269614 name:a269614now finalize:1497554242220
id:269614 name:a269614now finalize:1497554242321
id:269614 name:a269614now finalize:1497554242421
id:269614 name:a269614now finalize:1497554242521
id:269614 name:a269614now finalize:1497554248367
id:269614 name:a269614now finalize:1497554248467
id:269614 name:a269614now finalize:1497554248567
id:269614 name:a269614now finalize:1497554248667
id:269614 name:a269614now finalize:1497554249534
id:269614 name:a269614now finalize:1497554249634
id:269614 name:a269614now finalize:1497554249734
id:269614 name:a269614now finalize:1497554249835
id:269614 name:a269614now finalize:1497554255954
id:269614 name:a269614now finalize:1497554256055
id:269614 name:a269614now finalize:1497554256155
id:269614 name:a269614now finalize:1497554256255
id:269614 name:a269614now finalize:1497554256356
id:269614 name:a269614now finalize:1497554257285
id:269614 name:a269614now finalize:1497554257386
id:269614 name:a269614now finalize:1497554257486
id:269614 name:a269614now finalize:1497554257586
id:269614 name:a269614now finalize:1497554257686
id:269614 name:a269614now finalize:1497554268652
id:269614 name:a269614now finalize:1497554268753
id:269614 name:a269614now finalize:1497554268853
id:269614 name:a269614now finalize:1497554268953
id:269614 name:a269614now finalize:1497554269054
id:269614 name:a269614now finalize:1497554269154
id:269614 name:a269614now finalize:1497554277474
id:269614 name:a269614now finalize:1497554292852
id:269614 name:a269614now finalize:1497554301062

可以发现两个情况:

1.只有一个对象的finalize方法被执行了,也就是说这个死循环的finalize方法阻止了其他对象执行finalize方法

2.程序执行很快的一段时间后,finalize方法就开始执行,但是随着内存消耗的不断增加,finalize方法被执行的次数也就越来越少。

The above is the detailed content of How to use Java object destruction and finalize methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles