overexchange
overexchange

Reputation: 1

How does Java garbage collector work here?

In this query remove() method has following implementation.

 /**
   *  remove() removes "node" from this DList.  If "node" is null, do nothing.
   *  Performance:  runs in O(1) time.
   */
  public void remove(DListNode node) {
    if((node != null) && (node.listp == this)){
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
    this.size--;
  }

After the execution of this remove() method, There would not be any inward pointer pointing to object unless the user of DList class still points to this node using some reference variable.

My question:

When and How does garbage collector trash this object after none of the reference pointers point to this object? Because How can GC get control of that object without any reference to it?

Upvotes: 2

Views: 156

Answers (3)

user2864740
user2864740

Reputation: 61865

An object may be GC'ed/reclaimed at any point after it is no longer strongly reachable. An object is strongly reachable if and only if it can be reached (via strong references) from a GC root. That is, the GC reclaiming an object - if and when it chooses to do so - is merely a consequence of not being able to access said object.

Now, the one thing that Java guarantees is that it will try it's best (which may involve doing nothing) to free memory before throwing an OOM.

Even though there are no strong references from the code doesn't mean that the JVM isn't tracking the object or that it has vanished! The object still exists - even though it is not strongly reachable (read: not accessible) from user code - until/when such is actually GC'ed.

This allows for some interesting cases, eg.

Upvotes: 2

Elton Hoffmann
Elton Hoffmann

Reputation: 110

Java's GC does not trash an object as soon as it's not used anymore. Instead, GC runs from time to time, checking objects' usage and emptying memory.

You cannot tell GC to run arbitrarily, but you can request it to run by calling System.gc(). However, calling gc() does not run GC AT THIS TIME... it will only request the System to run it.

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35011

It is undefined. It could happen the next time the garbage collector runs (it can ONLY happy when the garbage collector runs), but that is not guarenteed - Not all garbage is necessarily cleaned with each gc run

Upvotes: 1

Related Questions