Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
Garbage collector removes an object in two "passes". In the first pass it just looks at the objects and, if necessary, marks it as "unnecessary to be deleted". If that object has overridden method finalize(), it is called. Or not, depending on your luck. On the second pass of the assembler object is removed and memory is freed. We don't know exactly when the garbage collector will start working. We don't know if the finalize() method will be called. On top of that, a strong reference to the object can be created while finalize() is running, and then it won't be deleted at all. On memory-hungry systems, this can easily lead to an OutOfMemoryError. The phantom references change the behavior of the garbage collector. If only phantom references are left on the object: 1.The finalize() method is called (if overridden) 2. if nothing has changed after finalize() and the object can still be deleted, the phantom reference to the object is placed into a special queue - ReferenceQueue.
5th Dec 2021, 2:52 PM
Alexey Kopyshev
Alexey Kopyshev - avatar
+ 2
The most important thing to understand when working with phantom references is that the object is not deleted from memory as long as its phantom reference is in that queue. It will be removed only after the clear() method is called on the phantom reference
5th Dec 2021, 2:54 PM
Alexey Kopyshev
Alexey Kopyshev - avatar