Katedral Pillon
Katedral Pillon

Reputation: 14864

What is the best way to clear a BST for garbage collection?

I want to clear a BST so as to take advantage of the garbage collector. So, to clear a BST, is it sufficient to set the root to null, so that I end up with a bunch of abandoned nodes with no pointers to them? Or is it better to set each node to null?

  1. Are the two methods equivalent?
  2. Would one of them cause memory leak?
  3. Would one be garbage collected faster than the other?

I am also concerned about weak reference and strong reference, etc.

Upvotes: 3

Views: 487

Answers (1)

Adam Stelmaszczyk
Adam Stelmaszczyk

Reputation: 19837

Any object that cannot be reached by any live thread will be eligible for garbage collection.

Based on that:

  1. Yes.
  2. No.
  3. Depends on the implementation of GC. Anyway, as a Java programmer, you can't control it. All you can do is have a trust that it will do its job just fine. Also, setting root to null is O(1), while nulling all references is O(n), where n is the number of nodes.

Conclusion:

Just set the root to null and let GC to traverse the tree in the good moment for him :)

Upvotes: 1

Related Questions