Weak Reference?

Hi,

Can anybody throw some light on Weak Reference, Strong Reference and Dangling Reference in java?

In which situation, we have to take care of these things? Is it mandatory to take care of these refernces, if so ,when? Please let me know the above things.

Thanks,

Ravindranath Y

[313 byte] By [yrnchowdarya] at [2007-11-27 3:42:44]
# 1

By default we work with strong references. They are used to prevent objects from being garbage collected; a strong reference from a reachable object keeps the object in memory.

There are three other types of references:

1. Soft references : Something like a cache. When you change an object, the old unchanged object is still available in case you'd want to 'undo' the change.

2. Weak references: Similar to soft references in that they allow references to objects without forcing the object to remain in memory. But soft references request the garbage collector to attempt to keep the object in memory but weak references do not.

3. Phantom references: They provide a means of delaying the reuse of memory occupied by an object even if it is finalized.

As far as dangling references are concerned, I don't think that applies in Java since it means a reference that remains after the object has been destroyed but in Java if there is a reference, the object will not be destoryed or garbage collected. So you can't have a dangling reference.

The references derive from the abstract class Reference in the java.lang.ref package.

These were added in Java 2 to augment the original memory management model; you'd use them for advanced management of your memory usage.

I've never used them myself, so I can't give you any examples.

nogoodatcodinga at 2007-7-12 8:46:21 > top of Java-index,Java Essentials,New To Java...
# 2

The only difference that I know between soft references and weak references is that weak references are guaranteed to be garbage collected, however soft references would be garbage collected only if JVM is running out of memory.

Phantom references are objects on which finalize method has been run. So finalize method does not run on phantom references. Now when would you in real life use class java.lang.ref.PhantomReference for large objects which you dont want to take the risk of being resurrected.

As per

http://java.sun.com/developer/technicalArticles/ALT/RefObj/

Weakly Reachable

An object is weakly reachable when the garbage collector finds no strong or soft references, but at least one path to the object with a weak reference. Weakly reachable objects are finalized some time after their weak references have been cleared. The only real difference between a soft reference and a weak reference is that the garbage collector uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.

A phantom reference is quite different than either SoftReference or WeakReference. Its grip on its object is so tenuous that you can't even retrieve the object -- its get() method always returns null. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue, as at that point you know the object to which it pointed is dead. How is that different from WeakReference, though?

The difference is in exactly when the enqueuing happens. WeakReferences are enqueued as soon as the object to which they point becomes weakly reachable. This is before finalization or garbage collection has actually happened; in theory the object could even be "resurrected" by an unorthodox finalize() method, but the WeakReference would remain dead. PhantomReferences are enqueued only when the object is physically removed from memory, and the get() method always returns null specifically to prevent you from being able to "resurrect" an almost-dead object.

What good are PhantomReferences? I'm only aware of two serious cases for them: first, they allow you to determine exactly when an object was removed from memory. They are in fact the only way to determine that. This isn't generally that useful, but might come in handy in certain very specific circumstances like manipulating large images: if you know for sure that an image should be garbage collected, you can wait until it actually is before attempting to load the next image, and therefore make the dreaded OutOfMemoryError less likely.

Second, PhantomReferences avoid a fundamental problem with finalization: finalize() methods can "resurrect" objects by creating new strong references to them. So what, you say? Well, the problem is that an object which overrides finalize() must now be determined to be garbage in at least two separate garbage collection cycles in order to be collected. When the first cycle determines that it is garbage, it becomes eligible for finalization. Because of the (slim, but unfortunately real) possibility that the object was "resurrected" during finalization, the garbage collector has to run again before the object can actually be removed. And because finalization might not have happened in a timely fashion, an arbitrary number of garbage collection cycles might have happened while the object was waiting for finalization. This can mean serious delays in actually cleaning up garbage objects, and is why you can get OutOfMemoryErrors even when most of the heap is garbage.

With PhantomReference, this situation is impossible -- when a PhantomReference is enqueued, there is absolutely no way to get a pointer to the now-dead object (which is good, because it isn't in memory any longer). Because PhantomReference cannot be used to resurrect an object, the object can be instantly cleaned up during the first garbage collection cycle in which it is found to be phantomly reachable. You can then dispose whatever resources you need to at your convenience.

Arguably, the finalize() method should never have been provided in the first place. PhantomReferences are definitely safer and more efficient to use, and eliminating finalize() would have made parts of the VM considerably simpler. But, they're also more work to implement, so I confess to still using finalize() most of the time. The good news is that at least you have a choice.

kilyasa at 2007-7-12 8:46:21 > top of Java-index,Java Essentials,New To Java...
# 3
Now can you memorize that for your interview?
DrLaszloJamfa at 2007-7-12 8:46:21 > top of Java-index,Java Essentials,New To Java...
# 4
> Now can you memorize that for your interview?I havenot come across a lot of candidates who know these details, so if even if one doesnot, I dont thing the interviewer would consider this a major handicap.
kilyasa at 2007-7-12 8:46:21 > top of Java-index,Java Essentials,New To Java...
# 5

An example of phantom reference usage

// Create the phantom reference.

ReferenceQueue rq = new ReferenceQueue();

PhantomReference pr = new PhantomReference(object, rq);

// Wait until the object is about to be reclaimed.

try {

while (true) {

Reference r = rq.remove();

if (r == pr) {

// The object is about to be reclaimed.

// Clear the referent so that it can be reclaimed.

r.clear();

}

}

} catch (InterruptedException e) {

}

kilyasa at 2007-7-12 8:46:21 > top of Java-index,Java Essentials,New To Java...