JavaRush /Java Blog /Random EN /Object lifecycle

Object lifecycle

Published in the Random EN group
Hello! I think you won’t be too surprised if you are told that the amount of memory on your computer is limited :) Even a hard drive, which is many times larger than RAM, can be packed to capacity with your favorite games, TV shows and more. To prevent this from happening, you need to monitor the current state of the memory and delete unnecessary files from the computer. What does Java programming have to do with all this? Direct! After all, when creating any object by a 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 in memory.Object life cycle - 1But how long do you think all these objects exist? Do they “live” all the time while 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 consider this process :) Especially since it is very important for understanding 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 required amount of memory to create the object. Then she creates a link to it, in our case cat, to be able to track it. After that, all variables are initialized, the constructor is called, and now - 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 on the second line. There was only one link to it, and now this link has been assigned null. Since there are no links left on the Lamborghini Diablo, it becomes “garbage”. The link does not need to be reset:
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 have created a second object, after which we took a reference lamborghiniand assigned this new object to it. Lamborghini GallardoThere are now two 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, the Garbage Collector, GC, comes into play.
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 in vain that we chose a picture with a robot vacuum cleaner for its image. 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? Well, in the case of Java objects, the garbage collector does it for you. The Garbage Collector runs multiple times during your program's run: you don't need to call it specifically and issue commands, although it is technically possible. Later we will talk about it and analyze the process of its work in more detail. At the moment when the garbage collector got to the object, just before its destruction, a special method is called on the object -finalize(). It can be used to release some extra resources that the object was using. The method finalize()belongs to the Object. That is, along with equals(), hashCode()and toString(), with which you have already met earlier, any object has it. It differs from other methods in that it is...how shall I say...very capricious. Namely, before the object is destroyed, it is not always called. Programming is a precise thing. The programmer tells the computer to do something, and the computer does it. I suppose you are already used to this behavior, and at first it may be difficult for you to accept the idea: “Before objects are destroyed, the finalize()class method is called Object. Or not called. If we get lucky!" However, this is true. The Java machine itself determines whether to call the methodfinalize()on a case-by-case basis 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 nullify the only reference to it. And so - a million times. We have 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, on my computer it worked only 37346 times! That is, only in 1 case out of 27, the Java machine I installed made the decision to call the method finalize()- in other cases, garbage collection took place without it. Try to run this code for yourself: most likely, the result will be different. As you can see, finalize()it is difficult to call a reliable partner :) Therefore, a little advice for the future: do not rely on the methodfinalize()in the case of the release of some critical resources. Maybe the JVM will call it, or maybe not. Who knows? If your object during its lifetime occupied some resources that are super important for performance, for example, kept a database connection open, it’s better to create a special method in your class to release them and call it explicitly when the object is no longer needed. So you will know for sure that the performance of your program will not suffer. At the very beginning, we said that working with memory and garbage collection is very important, and this is true. Improper handling of resources and misunderstanding of the process of assembling unnecessary objects can lead to memory leaks. This is one of the most famous mistakes in programming. Code written incorrectly by a programmer can lead to that for newly created objects new memory will be allocated each time, while old, unnecessary objects will not be available for removal by the garbage collector. Since we have given an analogy with a vacuum cleaner robot, imagine what will happen if, before starting the robot, you scatter socks around the house, break a glass vase and leave a disassembled Lego constructor 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 that the vacuum cleaner cannot handle from there. The same principle applies to the garbage collector. 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 at that moment on the computer. For them, too, there will not be enough memory. Object life cycle - 4This is what the object lifecycle and garbage collector look like in Java. It does not need to be memorized: it is enough just to understand the principle of work. In the next lecture, we will talk about these processes in more detail, but for now, you can return to solving CodeGym problems :) Good luck!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION