Do you really know the destruction of objects in Java

  • 2021-11-30 00:06:30
  • OfStack

In daily development, we all know that Java memory cleaning is carried out through garbage collector, so how does it clean up useless objects?

The automatic memory reclamation of Java language is called garbage collection (Garbage Collection) mechanism, or GC for short. The garbage collection mechanism is used by JVM to free up memory occupied by objects that are no longer in use.

Java objects need to be cleaned up after use. Object cleanup is to free the memory occupied by the object. When creating an object, the user must use the new operator to allocate memory for the object. After the object is cleared, the system will automatically reclaim the memory, and no additional processing is required by the user. This is also a feature of Java language, which makes it easier for programmers to manage memory.

There are two main situations in which an object is collected as garbage.

1) Object has a reference beyond its scope.


{
    Object o = new Object();    //  Object o Objects beyond which objects are treated as garbage 
}

2) The object is assigned null


{
    Object o = new Object();
    o = null;    //  Object is assigned to the null Will be treated as rubbish 
}

An finalize () method of type protected is also provided in the Object class of Java, so any Java class can override this method and release the related resources occupied by the object in this method.

Then the question comes again. What the hell is finalize ()? Since this method of an object is called, it means that all classes will have this method (after all, all classes will be recycled), we naturally think of the root class Object of java. Go in and have a look?


protected void finalize() throws Throwable { }

The last line is actually found. It is a method with an empty implementation. Since it is protected, it means that the specific method can be left to the subclass to implement. We said before that the object will only be recycled if it is no longer pointed to by any reference. So is this really the case? Let's take a look at chestnuts


public class User {
private int money;

public int getMoney() {
return money;

}

public void setMoney(int money) {
this.money = money;

}
public void cool(){
String str=new String();
}

@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub

if(money>0){
System.out.println("error");

}else{
System.out.println("suceess");
}
super.finalize();

}

}

Here we rewrite the finalize () method. If a person has not run out of money before destruction, print that person as a failure, otherwise that person is a success. Here's our code in main ()


public class Test {
public static void main(String args[]){
User u1=new User(200);
new Object();
new User(100);

}

}

The running result actually has nothing! After running, there is not only u1 pointed by reference, but also new User (100) without any reference; I can't believe it's not recycled. What's going on here?

Let's see how it is explained in Thinking In Java

Objects in java are not always garbage collected, meaning objects may not be collected. As long as the program is on the verge of running out of storage space, garbage collector 1 will not actively recycle memory. If the program ends and garbage collector 1 does not release the space you created, the resources will be returned to the operating system as the program exits. So the above finalize () is only 1 and has not been called

If we want to see the effect, we can do the following:


public class Test {
public static void main(String args[]){
User u1=new User(200);

new Object();

new User(100);

System.gc();

}

}

System. gc (); Will force the system garbage collector to work, and the running effect will appear error
Description new User (100); The created object was recycled.

Note: Calling the System. gc () or Runtime. gc () methods does not guarantee that the collection operation will be executed, but only improves the possibility that the Java garbage collector will collect garbage as soon as possible.

Knowledge supplement:

In the heap area of the Java virtual machine, each object may be in one of three states.

1) Accessible state: When an object is created, it is always accessible as long as there are reference variables in the program that refer to it.

2) Resurrectible state: When the program no longer has any reference variables referencing the object, the object enters the resurrectible state. In this state, the garbage collector is ready to release the memory it occupies, and before releasing it, it calls the finalize () methods of it and other objects in the resurrectible state, which may make the object go back to the reachable state.

3) Untouchable state: After the Java virtual machine executes all the finalize () methods of resurrectable objects, the garbage collector does not really reclaim the memory it occupies until none of these methods makes the object go to the touchable state.

Summarize


Related articles: