search
HomeJavajavaTutorialIntroduction to methods to prohibit the use of finalize in Java

This article mainly introduces the prohibition of using the finalize method in Java. Friends who need it can refer to it

What is the finalize method

finalize The () method is defined in the Java.lang.Object class, which means that all classes can override this method. The Java garbage collector can only release memory allocated through new, so if your object is not a memory obtained through new, then the garbage collector does not know how to release the memory of the object.

In order to deal with this situation, java allows the finalize() method in the java.lang.Object class to be overloaded in the class.

How it works: Once the garbage collector is ready to release the storage space occupied by the object, its finalize() method will first be called, and the memory occupied by the object will not be actually reclaimed until the next garbage collection action occurs. .

The calling mechanism of the finalize function

The Java virtual machine specification does not strictly stipulate whether garbage collection should be performed and how it should be performed. Therefore, the calling mechanism mentioned here is not guaranteed to be suitable for all JVMs.

When is it called?

When will finalize be called? Generally speaking, it may not be called until the JVM starts garbage collection. The time point at which the JVM performs garbage collection is very uncertain and depends on various runtime environmental factors. It is precisely because of the uncertainty of the finalize function calling time that it leads to some of the shortcomings mentioned later.

Who will call?

A common JVM will call the finalize function through the GC's garbage collection thread. Since the garbage collection thread is very important (it is also an integral part of the JVM after all), in order to prevent the exception thrown by the finalize function from affecting the operation of the garbage collection thread, the garbage collection thread will perform a try catch when calling each finalize function. If When an exception is caught, it is discarded directly, and then the finalize function of the next invalid object is processed.

Why is it forbidden to use finalize()

1. The calling time is uncertain---there is a risk of wasting resources

The calling mechanism has been introduced earlier. Students should recognize the fact that "the timing of calling finalize is very uncertain". Therefore, if you release some scarce resources in finalize(), it may cause the scarce resources to wait for a long, long, long time before being released. This is a waste of resources! In addition, the resources carried by certain class objects (such as some JDBC classes) may themselves consume a lot of memory, and the delayed release of these resources will cause great performance problems.

2. May not be called - there is a risk of resource leakage

Many students think that finalize() will always be called, but this is not the case. In some cases, finalize() is not called at all. For example, when the JVM exits, the finalize functions of those objects in the memory may not be called.

It is estimated that some students are thinking of "runFinalizersOnExit" to ensure that all finalizes are called before the JVM exits. It is a pity and regret that this method has been abandoned since JDK 1.2. Even if this method is not abandoned, it still has a huge thread safety hazard!

As can be seen from the above, once you rely on finalize() to help you release resources, that is very bad (there is a risk of resource leakage)! Many times, performance problems caused by resource leaks are more serious and should not be underestimated.

3. The object may be resurrected when the finalize function is called.

Originally, the garbage collector will call the object only when it has expired (no reference). finalize function. However, if you encounter a perverted programmer, re-saving the reference to the object itself (that is, this) somewhere inside the finalize() function is equivalent to resurrecting yourself (because the object has new reference and is no longer in an invalid state). In order to prevent this weird thing from happening, the garbage collector can only check whether the object is still in an invalid state after each call to finalize(). This virtually increases the overhead of the JVM. Just mention it casually. As the JDK documentation stipulates, the JVM will only call finalize() at most once for each class object instance. Therefore, for those instances of fake corpses, finalize() will not be called when they actually die. Doesn't this seem weird?

4. Remember to catch exceptions yourself

Just mentioned when introducing the finalize() calling mechanism, once an exception is thrown outside the finalize function, it will be Caught and discarded by the garbage collection thread. In other words, the exception is ignored (the dangers of ignored exceptions are mentioned "here"). In order to prevent this kind of thing, you have to write a try catch statement for any code that may throw an exception in finalize() and catch it yourself.

5. Be careful about thread safety

Since finalize() is called by a garbage collection thread, it is not the same thread as your own code; even finalize() of different objects may be called by different garbage collection threads (such as using a "parallel collector" when). Therefore, when you access certain data in finalize(), you must always pay attention to thread safety issues.

Summarize

The above is the detailed content of Introduction to methods to prohibit the use of finalize in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

How do you test Java applications for platform compatibility?How do you test Java applications for platform compatibility?May 01, 2025 am 12:09 AM

ToeffectivelytestJavaapplicationsforplatformcompatibility,followthesesteps:1)SetupautomatedtestingacrossmultipleplatformsusingCItoolslikeJenkinsorGitHubActions.2)ConductmanualtestingonrealhardwaretocatchissuesnotfoundinCIenvironments.3)Checkcross-pla

What is the role of the Java compiler (javac) in achieving platform independence?What is the role of the Java compiler (javac) in achieving platform independence?May 01, 2025 am 12:06 AM

The Java compiler realizes Java's platform independence by converting source code into platform-independent bytecode, allowing Java programs to run on any operating system with JVM installed.

What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.