Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

memory - java - How can Garbage Collector quickly know which objects do not have references to them any more?

I understand that in Java, if an object doesn't have any references to it any more, the garbage collector will reclaim it back some time later.

But how does the garbage collector know that an object has or has not references associated to it?

Is garbage collector using some kind of hashmap or table?


Edit:

Please note that I am not asking how generally gc works. really, I am not asking that.

I am asking specifically that How gc knows which objects are live and which are dead, with efficiencies.

That's why I say in my question that is gc maintain some kind of hashmap or set, and consistently update the number of references an object has?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A typical modern JVM uses several different types of garbage collectors.

One type that's often used for objects that have been around for a while is called Mark-and-Sweep. It basically involves starting from known "live" objects (the so-called garbage collection roots), following all chains of object references, and marking every reachable object as "live".

Once this is done, the sweep stage can reclaim those objects that haven't been marked as "live".

For this process to work, the JVM has to know the location in memory of every object reference. This is a necessary condition for a garbage collector to be precise (which Java's is).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...