Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection behavior with isolated cyclic references?

If I have two objects on the heap referring to each other but they are not linking to any reference variable then are those objects eligible for garbage collection?

like image 212
Warrior Avatar asked Jan 09 '09 07:01

Warrior


People also ask

Does garbage collector handle cyclic references?

yes Java Garbage collector handles circular-reference! How? There are special objects called called garbage-collection roots (GC roots). These are always reachable and so is any object that has them at its own root.

What is garbage collection cycle?

A GC cycle that includes concurrent mark operations aims to trace all reachable objects and complete processing at the same time as the heap is exhausted. Continuous adjustments are made to the start time of each cycle to get as close to heap exhaustion as possible.

What are different garbage collection methods?

There are two ways to do it : Using System. gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector. Using Runtime.

What is reference counting garbage collector?

Reference counting garbage collection is where each object has a count of the number of references to it. Garbage is identified by having a reference count of zero. An object's reference count is incremented when a reference to it is created, and decremented when a reference is destroyed.


2 Answers

Yes, they are. Basically the GC walks from "known roots" (static variables, local variables from all stack frames in alll threads) to find objects which can't be garbage collected. If there's no way of getting to an object from a root, it's eligible for collection.

EDIT: Tom pointed this out, which I thought was worth lifting into the answer itself:

Technically, static variables are not roots - they are referenced by classes which are referenced by class loaders which are referenced by classes which are referenced by object which are referenced by root references.

The difference is likely to be irrelevant most of the time, but it's good to know :)

like image 144
Jon Skeet Avatar answered Oct 19 '22 03:10

Jon Skeet


Check this out: How does Java Garbage Collector Handle Self References.

You may want to check java.lang.ref.WeakReference

like image 21
Hosam Aly Avatar answered Oct 19 '22 03:10

Hosam Aly