gub
gub

Reputation: 5229

Will GC collect an object referred to by a SoftReference and a WeakReference?

I have a cache built from a Map to SoftReferences. When they are added they get put into another queue to be lazily compressed down via gzip or some such. My idea is this: I want to have WeakReferences to the objects in the compress queue, so that when the compressor task gets to the object, if it is already gone we needn't bother compressing it - and also that the compressor's queue doesn't keep objects alive that would otherwise be GC'd.

So if there is exactly one SoftReference and one WeakReference, does the semantic of SoftReference apply still?

Upvotes: 2

Views: 428

Answers (3)

hqt
hqt

Reputation: 30284

You should notice that Weak Reference always collect before Soft Reference. And Soft Reference often use to cache something.

It means: at that time, no longer it needs to survive, but, at sometimes in the future, maybe you need it again, and Java will not work again to instance a new object.

Upvotes: 0

jutky
jutky

Reputation: 3965

yes, there is no problem to GC the object that has as many soft/weak references as you want, until it has almost one strong reference.

Upvotes: 2

Hendrik Brummermann
Hendrik Brummermann

Reputation: 8312

Yes the semantic of SoftReferences still applies: SoftReferences are stronger than WeakReferences.

WeakReferences are basically treated as non existing for the GC. So an object that is only weakly reachable may be GCed immediately. Objects only reachable by a SoftReferences as the strongest type, however, are only considered for GCing if demands on memory needs to be fullfilled.

So if there are both soft and weak references, the semantic of SoftReference is applied.

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed.

http://download.oracle.com/javase/6/docs/api/java/lang/ref/WeakReference.html

Soft reference objects, which are cleared at the discretion of the garbage collector in response to memory demand. Soft references are most often used to implement memory-sensitive caches.

http://download.oracle.com/javase/6/docs/api/java/lang/ref/SoftReference.html

Upvotes: 3

Related Questions