Rohit
Rohit

Reputation: 450

How GC mark non-reachable object as it is already not reachable

I believe this is a simple question but i am having small doubt in my understanding. my concern is whenever GC initiate garbage collecting, it mostly involves three steps:

  1. Mark
  2. Sweep
  3. Compacting

While marking phase of GC, It traverse from GC root to all objects and do the marking of non-reachable objects. which i have read it in many blocks.

Here my doubt is, While traversing from GC root GC will only be visiting to live object(which is being referenced in the tree). Right! Then definitely there would no way to reach to non-reachable object. So How GC would be marking to non-reachable object as GC can't reach to them. Please help me out to understand this concept. Thanks!

Upvotes: 0

Views: 260

Answers (3)

Stephen C
Stephen C

Reputation: 718986

How GC mark non-reachable object as it is already not reachable

Non-reachable objects are not marked.

The idea is that the process of marking visits all of the objects that are reachable, and sets the mark on each one it finds. Then the sweep phase gets rid of the objects that are NOT marked.

So how does the GC find the objects that are not been marked?

Well, all objects have a header block that includes the mark bit and other things as well as the size of the object. Objects are stored consecutively in memory. So if you have the address of the first object, you just have to add the object size and header size to that address ... and you have the address of the next object.

That's what the sweeper does. It scans through all of the objects, checking to see if they are marked or not. The objects that are not marked are then deleted.

(I'm simplifying a lot ...)

Upvotes: 2

the8472
the8472

Reputation: 43052

While the mark phase is a graph traversal starting from roots the sweep phase the collector can perform a (parallelizable) linear scan over memory regions, identifying all objects based on known layouts (headers in most JVM implmentations, fixed sizes of GC slots in some other runtimes)

Upvotes: 1

Alexey Ragozin
Alexey Ragozin

Reputation: 8379

  • Mark - mark live object starting from GC roots
  • Sweep - traverse heap to identify non-marked objects
  • Compact - move objects in heap to make free memory continuous (fragmentation counter measure)

Upvotes: 0

Related Questions