Question:
Let's say we have a line like this:
Object object = new Object()
Scenario:
- An object
new Object()
was created, but a reference to it has not yet been assigned to the variableobject
. -
GC
was called. There is no reference to our object and it deletes it. - The
object
variable remains without an object.
I don’t think this is possible, but I don’t understand why.
Answer:
Because the link is always there. Well, think for yourself, if right after the end of the constructor's work it is not there, then what do we then assign to the variable? If you look at the object creation bytecode, you will see something like
0: new #2 // class java/lang/String
// память заказана, ссылка на неициализированный объект положена в стек операндов
3: dup // ссылка раздублирована
4: invokespecial #3 // Method java/lang/String."<init>":()V
// один экземпляр ссылки передан параметром в конструктор и там пропал
7: astore_0 // второй экземпляр записали в локальную переменную
these references lying on the operand stack are also taken into account by the garbage collector, as well as references from variables.