Garage Collection OCJPexam

Given:

public class GC { private Object o; private void doSomethingElse(Object obj) { o = obj; } public void doSomething() { Object o = new Object(); // line 5 doSomethingElse(o); o = new Object(); // line 7 doSomethingElse(null); o = null; } } 

When the doSomething method is called, after which the line creates the object created in line 5 become available for garbage collection?

I think the shuld answer will be after line 7..bt the answer is after line 8..explain me, where I am wrong ..

+4
source share
3 answers

An object can only be garbage collection when it becomes inaccessible. In your code, after line 7, you can access the object created in line 5. through the this.o field.

After line 8. this.o == null , and therefore the object created on line 5. becomes inaccessible.

Reachability Rules:

+3
source

The o object on line 5 is a local variable for the doSomething() method.

He will become an orphan after line 8.

Since both local and global links will no longer reference the object.

Edit:

Although it is very late, but I hope that someday it can help someone.

You can get such events by using a library I'm developing called gcRadar . It provides events when the object is orphaned and after the actual garbage collection of the object.

Any suggestions for improvement in the library are welcome.

+2
source

For an object accessible to the GC, it does not guarantee that the object will be GC'ed immediately. It really depends on the implementation of the Civil Code.

Since you are talking about Java, it also depends on the state of the program being launched. The program may be interpreted or may be JIT'ed.

If it is interpreted, I think it will be available to the GC on line 8 when you set it to null. If it is JIT'ed, it can (logically) be garbage collected on line 7 because the newly created object will not be used.

0
source

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


All Articles