In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to implement garbage collection mechanism in Java. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
1. Introduction
The programmer is responsible for the creation and destruction of objects in C _ blank +. Programmers usually ignore the destruction of useless objects. Due to this oversight, at some point, in order to create a new object, there may not be enough memory available, and the whole program will terminate abnormally.
Java, causing OutOfMemoryErrors. Programmers do not need to care about all objects that are no longer in use.
The garbage collection mechanism automatically destroys these objects. The garbage collection mechanism is the best example of a daemon thread because it always runs in the background.
The main goal of the garbage collection mechanism is to free heap memory by destroying inaccessible objects.
2. Important Clause 2.1 inaccessible objects
If an object does not contain any references to it, it is called an inaccessible object. Also note that objects belonging to the isolation island are also inaccessible.
Integer I = new Integer (4); / / the new Integer object can be accessed through a reference in'i'. The I = null;// Integer object is no longer available.
2.2 eligibility for garbage collection
If an object is not accessible, it is said to be eligible for GC (garbage collection). In the figure above, after I = null; integer object 4 in the heap area is eligible for garbage collection.
3. The method of making the object conform to the GC condition
Even though programmers are not responsible for destroying useless objects, it is highly recommended that objects be made inaccessible (and therefore eligible for GC) if they are no longer needed.
There are usually four different ways to make objects suitable for garbage collection.
Dereference variable
Reassign reference variables
Objects created inside a method
Isolated island
All of the above methods with examples are discussed in a separate article: how to make objects meet garbage collection conditions
4. How to request JVM to run garbage collector
Once we make the object eligible for garbage collection, the garbage collector may not destroy it immediately. Whenever JVM runs the garbage collector program, only the object is destroyed. But when JVM runs Garbage Collector, we can't predict it.
We can also ask JVM to run the garbage collector. There are two ways to do this:
Use the System.gc () method: the system class contains the static method gc () to request JVM to run the garbage collector.
Use the Runtime.getRuntime (). Gc () method: the runtime class allows the application to interact with the JVM of the running application. Therefore, by using its gc () method, we can ask JVM to run the garbage collector.
/ demonstrate Java program public class Test {public static void main (String [] args) throws InterruptedException {Test T1 = new Test (); Test T2 = new Test () that requests JVM to run garbage collector; / / dereferencing variable T1 = null; / / requesting JVM to run garbage collector System.gc (); / / dereferencing variable T2 = null / / request JVM to run the garbage collector Runtime.getRuntime (). Gc ();} @ Override / / before garbage collection, call the finalize method protected void finalize () throws Throwable {System.out.println ("garbage collector call"); System.out.println ("object garbage collection:" + this);}}
Output:
The garbage collector calls the
Object garbage collection: haiyong.Test@7ad74083
The garbage collector calls the
Object garbage collection: haiyong.Test@7410a1a9
There is no guarantee that either of these two methods will run the garbage collector.
Calling System.gc () is equivalent to calling: Runtime.getRuntime () .gc ()
Just before destroying the object, the garbage collector calls the object's finalize () method to perform the cleanup activity. Once the finalize () method is complete, the garbage collector destroys the object.
The finalize () method exists in the Object class with the following prototype.
Protected void finalize () throws Throwable
According to our requirements, we can override the finalize () method to perform our cleanup activities, such as closing database connections.
The garbage collector instead of the finalize () method called by JVM. Although the garbage collector is one of the modules of JVM.
The object class finalize () method is available for implementation, so it is recommended that you override the finalize () method to handle system resources or perform other cleanups.
The finalize () method is never called multiple times for any given object.
If the finalize () method throws an uncaught exception, it ignores the exception and terminates the object.
For an example of the finalize () method, see garbage collection in set 10 of the output of the Java program
5. Give an example
Use the concept of garbage collector.
Suppose you go to a byte beat internship, and they tell you to write a program to calculate the number of employees working in the company (excluding interns). To make this program, you must use the concept of garbage collector.
This is the actual task you got at the company:-
Q: write a program to create a class called Employee, which has the following data members.
An ID that stores the unique ID assigned to each employee.
Employee name.
Employee age.
In addition, the following methods are provided-
A parameterized constructor used to initialize the name and age. ID should be initialized in this constructor.
The method show () that displays ID, name, and age.
The method showNextId () that displays the ID of the next employee.
Beginners who are not familiar with the garbage collection mechanism may write code like this:
/ / the program class Employee {private int ID; private String name; private int age; private static int nextId=1; / / which calculates the number of employees working in the company is static because it is common among all objects and public Employee (String name,int age) {this.name = name; this.age = age; this.ID = nextId++ is shared by all objects. } public void show () {System.out.println ("Id=" + ID+ "\ nName=" + name+ "\ nAge=" + age);} public void showNextId () {System.out.println ("Next employee id will be=" + nextId);}} class UseEmployee {public static void main (String [] args) {Employee E=new Employee ("GFG1", 33); Employee F=new Employee ("GFG2", 45); Employee G=new Employee ("GFG3", 25); E.show (); F.show () G.show (); E.showNextId (); F.showNextId (); G.showNextId (); {/ / this is a child block reserved for all interns. Employee X=new Employee ("GFG4", 23); Employee Y=new Employee ("GFG5", 21); X.show (); Y.show (); X.showNextId (); Y.showNextId ();} / / after the curly braces, X and Y are removed. So now it should show that nextId is 4. E.showNextId (); / / the output of this line should be 4, but it will give 6 as output. }}
Output:
Now get the correct output:
Now the garbage collector (gc) will see two free objects. Now decreasing nextId,gc (garbage collector) will only call the method finalize () when our programmer overrides it in our class. As mentioned earlier, we must request gc (garbage collector), and to do this, we must write the following three steps before closing the braces of the subblock.
Set the reference to null (that is, X = Y = null;)
Call, System.gc ()
Call, System.runFinalization ()
Now the correct code for calculating the number of employees (excluding interns)
/ / the correct code for calculating the number of employees excluding interns is class Employee {private int ID; private String name; private int age; private static int nextId=1; / / it is static because it remains common among all objects and is shared by all objects public Employee (String name,int age) {this.name = name; this.age = age; this.ID = nextId++ } public void show () {System.out.println ("Id=" + ID+ "\ nName=" + name+ "\ nAge=" + age);} public void showNextId () {System.out.println ("Next employee id will be=" + nextId);} protected void finalize () {--nextId; / / in this case, gc calls finalize () twice for two objects. }} / / it is the closing parenthesis of the Employee class class UseEmployee {public static void main (String [] args) {Employee E=new Employee ("GFG1", 33); Employee F=new Employee ("GFG2", 45); Employee G=new Employee ("GFG3", 25); E.show (); F.show (); G.show (); E.showNextId (); F.showNextId (); G.showNextId (); {/ / this is a child block reserved for all interns. Employee X=new Employee ("GFG4", 23); Employee Y=new Employee ("GFG5", 21); X.show (); Y.show (); X.showNextId (); Y.showNextId (); X = Y = null; System.gc (); System.runFinalization ();} E.showNextId ();}}
Output:
This is the end of the article on "how to implement garbage collection mechanism in Java". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.