Question about GC

This is quesiton taken from the Java exam,

How many objects are suitable for the gabare collection in # 1?

public class Main { Integer x = 32768; public static void main(String[] args) { Main m = new Main(); m = null; // #1 } } 

I thought that it just compiles Integer x, does the GC even compile the main object m?

+4
source share
6 answers

Yes, it collects the main object. Since the integer is not a separate object separately (it is a member of Main), and is not a pointer, it will not be assembled separately, but only as part of Main.

+5
source

Two objects can be removed by the garbage collector.

The object assigned to m is no longer available, and Integer inside Main.

Edit:. You may ask yourself: "Is it possible that I somehow access the object at this stage?" If the answer is no, the garbage collector can delete it.

+3
source

One confusion you may encounter is that the main method can be called even if it is not the main object. This is because it is a static method. Similarly, "Integer x" exists only as a field in the main object. Therefore, when you create a new Core Object m, you also create an integer mx as part of m. Then, when you set m to null, the object that was previously mentioned by m is garbage and can be collected.

Now that it is assembled, this is a completely different matter. In fact, there are no guarantees; however, since its use has been so localized, it will almost certainly be taken care of the next minor assembly / cleaning / selection of your favorite terminology.

+2
source

Can. There is no longer a link to it, so it has the right to collect garbage.

+1
source

An instance of Main has the right to collect garbage, and, as a rule, Integer will also have the right to participate. But an Integer instance can also be cached by the Integer class if it is configured for this (see this answer ).

Usually only integers between -128 and 127 are cached when using Integer # valueOf (int) (used for autoboxing), but the upper limit can be increased by setting the system property java.lang.Integer.IntegerCache.high

0
source

My observations using the recent OpenJDK showed that only after the method exits, any links that it lost are actually collected. I did not expect this, but it happened. Extracting these lines of code into another method, which then returned back to main (), allowed us to build an instance.

I think this is a stupid question. (EDIT: I mean the exam question! Without offending the author!) All this is how you define "suitable." In my case, I would say that after there were no references, the instance had the right to collect, it is just that it will never be assembled until the method returns.

0
source

Source: https://habr.com/ru/post/1308028/


All Articles