2

I have a question on SoftReferences WeakReferences in Java.

What i know is:

GC uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

Does that mean GC never runs the finalize() method on WeakReferences?

Thanks

Colin D
  • 5,641
  • 1
  • 23
  • 35
Anshul
  • 121
  • 1
  • 1
  • 4
  • You should not assume `finalize()` methods will _ever_ be called under any circumstances -- indeed, you should avoid their use at all. See Effective Java item 7. – Louis Wasserman Aug 30 '12 at 16:28
  • @LouisWasserman: But, the document I refereed in my answer saying, finalze() must be called. Isn't it contradictory? – kosa Aug 30 '12 at 16:31
  • EJ quote: "One shortcoming of finalizers is that there is no guarantee they’ll be executed promptly [JLS, 12.6]. It can take arbitrarily long between the time that an object becomes unreachable and the time that its finalizer is executed. This means that you should never do anything time-critical in a finalizer." To be sure, I didn't make that as clear as I could have...but honestly, using `finalize()` in the first place remains a terrible code smell. – Louis Wasserman Aug 30 '12 at 19:56

2 Answers2

2

As per The Truth About Garbage Collection

If a class defines a finalizer, then any instance of that class must have the finalizer called prior to deallocation. This means that deallocation is delayed by the inclusion of a finalizer.

Based on this my understanding is, irrespective of Week/Soft, if finalize defined, it will be called.

kosa
  • 65,990
  • 13
  • 130
  • 167
0

I don't follow your line of reasoning, but the finalizer is definitely always called. As soon as an object becomes finalizable, all soft/weak references to it will be cleared. So the refs can be observed as null before finalization.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436