1

What I know about Java's garbage collector is that it handles everything needed, but my concern is efficiency.

Some other languages, like Python — as far as I know —, can help the garbage collector by actually doing this:

objectReference = none

Does this works in Java, in such a way the programmer can almost free Heap memory in a efficient way by assigning variables to null? If yes, how efficient is this, compared to C's manually freeing memory with the free() function?

vefthym
  • 7,422
  • 6
  • 32
  • 58
  • 4
    see [Does assigning objects to null in Java impact garbage collection?](http://stackoverflow.com/questions/449409/does-assigning-objects-to-null-in-java-impact-garbage-collection). Also, we need to remember that algos keep changing from JDK to JDK. – Sabir Khan Feb 12 '16 at 04:59
  • Your answer may also be in this post: http://stackoverflow.com/questions/1481178/how-to-force-garbage-collection-in-java – vefthym Feb 12 '16 at 05:00
  • 1
    I'm not sure that you should tag this question as _python_ even though you did mention it. You are going to attract python programmers who can't answer the question. Python really bares no importance for this question. The _c_ tag is probably ok as you are asking about comparison of the language. – Matthew Feb 12 '16 at 05:02

2 Answers2

2

Variables don't exist anymore after they go out of scope, e.g. when method returns, so there's very rarely any benefit from null'ing a variable early.

Fields have a lifetime equal to the owning object, so if an object will continue to exist for a while, but you know the field reference will no longer be needed, then null'ing the field may allow earlier GC of the referenced object.

Whether to bother doing that depends on how much longer the owning object will stay around, and how big the referenced object is. It's rarely worth it.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • If escape analysis proves that a reference never exits the scope, then an Object could be GCed (or more specifically *eligible for GC*) but the field's value' itself could be copied into another reference and then used. – TheLostMind Feb 12 '16 at 05:52
0

setting a reference to null sorta helps. If that was the only reference to the object, then the garbage collector will have the freedom to clean up the memory for that object when it sees fit. At best you can signal to the garbage collector when a good time would be to free up memory with System.gc(), but it's still ultimately a suggestion and doesn't force it.

Jack Ammo
  • 280
  • 1
  • 5