java – Can gc delete a newly created object prior to assigning to a variable?


Let's say we have a line like this:

Object object = new Object()


  1. An object new Object() was created, but a reference to it has not yet been assigned to the variable object .
  2. GC was called. There is no reference to our object and it deletes it.
  3. The object variable remains without an object.

I don’t think this is possible, but I don’t understand why.


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.

Scroll to Top