JavaRush /Java Blog /Random EN /Object life cycle

Object life cycle

Published in the Random EN group
Hello! I think you won’t be too surprised if we tell you that the memory size on your computer is limited :) Even a hard drive, which is many times larger than RAM, can be filled to capacity with your favorite games, TV series, and so on. To prevent this from happening, you need to monitor the current state of memory and delete unnecessary files from your computer. What does Java programming have to do with all this? Direct! After all, when any object is created by the Java machine, memory is allocated for it. In a real large program, tens and hundreds of thousands of objects are created, each of which has its own piece of memory allocated. Object life cycle - 1But how long do you think all these objects exist? Do they “live” the entire time our program is running? Of course no. With all the advantages of Java objects, they are not immortal :) Objects have their own life cycle. Today we will take a little break from writing code and look at this process :) Moreover, it is very important for understanding the operation of the program and managing resources. So, where does the life of an object begin? Like a person - from his birth, that is, creation.
Cat cat = new Cat();//вот сейчас и начался vital цикл нашего an object Cat!
First, the Java Virtual Machine allocates the necessary amount of memory to create the object. Then she creates a link to it, in our case - catto be able to track it. After this, all variables are initialized, the constructor is called, and lo and behold, our fresh object is already living its own life :) The lifespan of objects is different, there are no exact numbers here. In any case, for some time it lives inside the program and performs its functions. To be precise, an object is “alive” as long as there are references to it. As soon as there are no links left, the object “dies”. For example:
public class Car {

   String model;

   public Car(String model) {
       this.model = model;
   }

   public static void main(String[] args) {
       Car lamborghini  = new Car("Lamborghini Diablo");
       lamborghini = null;

   }

}
In the method, main()the Lamborghini Diablo car object ceases to be alive already on the second line. There was only one link to it, and now this link has been assigned null. Since there are no references left to the Lamborghini Diablo, it becomes “junk”. It is not necessary to reset the link:
public class Car {

   String model;

   public Car(String model) {
       this.model = model;
   }

   public static void main(String[] args) {
       Car lamborghini  = new Car("Lamborghini Diablo");

       Car lamborghiniGallardo = new Car("Lamborghini Gallardo");
       lamborghini = lamborghiniGallardo;
   }

}
Here we created a second object, after which we took the reference lamborghiniand assigned it to this new object. There are now Lamborghini Gallardotwo references to the object, but Lamborghini Diablonone to the object. Therefore the object Diablobecomes garbage. And at this moment, the built-in Java mechanism called the garbage collector, or in other words - Garbage Collector, GC, comes into operation.
Object life cycle - 2
The garbage collector is an internal Java mechanism that is responsible for freeing memory, that is, removing unnecessary objects from it. It was not for nothing that we chose a picture with a robot vacuum cleaner to depict it. After all, the garbage collector works in much the same way: in the background, it “travels” through your program, collects garbage, and at the same time you practically do not interact with it. Its job is to remove objects that are no longer used in the program. Thus, it frees up memory in the computer for other objects. Do you remember at the beginning of the lecture we said that in ordinary life you have to monitor the state of your computer and delete old files? So, in the case of Java objects, the garbage collector does this for you. Garbage Collector is launched many times during the operation of your program: it does not need to be called specifically and given commands, although this is technically possible. Later we will talk more about it and analyze the process of its work in more detail. At the moment when the garbage collector reaches the object, just before its destruction, a special method is called on the object - finalize(). It can be used to free up some additional resources that the object was using. The method finalize()belongs to the class Object. That is, along with equals(), hashCode()and toString(), which you already met earlier, any object has it. Its difference from other methods is that it is... how to put it... very capricious. Namely, it is not always called before destroying an object. Programming is a precise thing. The programmer tells the computer to do something, and the computer does it. You are probably already used to this behavior, and it may be difficult for you at first to accept the idea: “Before objects are destroyed, the finalize()class method is called Object. Or it is not called. If we get lucky!" However, this is true. The Java machine itself determines whether to call the method finalize()in each specific case or not. For example, let's try to run the following code for the sake of experiment:
public class Cat {

   private String name;

   public Cat(String name) {
       this.name = name;
   }

   public Cat() {
   }

   public static void main(String[] args) throws Throwable {

       for (int i = 0 ; i < 1000000; i++) {

           Cat cat = new Cat();
           cat = null;//вот здесь первый an object становится доступен сборщику мусора
       }
   }

   @Override
   protected void finalize() throws Throwable {
       System.out.println("Объект Cat уничтожен!");
   }
}
We create an object Catand in the next line of code we reset the only reference to it. And so - a million times. We've explicitly overridden the method finalize(), and it should print the string to the console a million times, each time before destroying the object Cat. But no! To be precise, it only ran 37,346 times on my computer! That is, only in 1 case out of 27 did the Java machine I installed decide to call a method finalize()- in other cases, garbage collection proceeded without this. Try running this code yourself: most likely, the result will be different. As you can see, finalize()it’s hard to call it a reliable partner :) Therefore, a little advice for the future: you should not rely on the method finalize()in the case of freeing up some critical resources. Maybe the JVM will call it, maybe not. Who knows? If during its lifetime your object occupied some resources that were super important for performance, for example, it kept an open connection to the database, it is better to create a special method in your class to free them and call it explicitly when the object is no longer needed. This way you will know for sure that the performance of your program will not suffer. At the very beginning we said that memory management and garbage removal are very important, and this is true. Inappropriate handling of resources and lack of understanding of the process of assembling unnecessary objects can lead to memory leaks. This is one of the most famous programming mistakes. Incorrectly written code by the programmer can result in new memory being allocated each time for newly created objects, while old, unnecessary objects are not available for removal by the garbage collector. Since we made an analogy with a robot vacuum cleaner, imagine what would happen if, before starting the robot, you scattered socks around the house, broke a glass vase and left a disassembled Lego set on the floor. The robot, of course, will try to do something, but at one point it will get stuck.
Object life cycle - 3
For it to work properly, you need to keep the floor in good condition and remove everything from there that the vacuum cleaner cannot handle. The garbage collector works on the same principle. If there are many objects left in the program that it cannot collect (like a sock or Lego for a robot vacuum cleaner), at one point the memory will run out. And not only the program you wrote will freeze, but also all other programs running on the computer at that moment. There won't be enough memory for them either. This is what the object lifecycle and garbage collector look like in Java. There is no need to memorize this: just understand the principle of operation. In the next lecture we will talk about these processes in more detail, but for now you can return to solving JavaRush problems :) Good luck!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION