Suppose I have a weak reference to a car which has an ordinary (strong) reference to an engine. No other references to the car or the engine exist. Can the engine be garbage collected?
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
//eligible for garbage collection. Weak References: Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. This type of reference is used in WeakHashMap to reference the entry objects .
A weak reference is a way to have some pointer to an object that does have any reference (strong reference). In . NET, any normal reference to another object is a strong reference . That is, when you declare a variable of a type that is not a primitive/value type, you are declaring a strong reference.
A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can still obtain a strong reference to it and prevent it from being collected.
Yes it can, that is exactly how weak references are designed to work. The weak reference is the root that your object has to the application, even though the object may have other strong references it is the root reference that matters and since the root reference is a weak reference the object will be a candidate for garbage collection.
For more information please see WeakReference
class documentation:
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.
Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references. At the same time it will declare all of the formerly weakly-reachable objects to be finalizable. At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues.
FYI, along with WeakReference
, Java offers two other subclasses of Reference
: SoftReference
and PhantomReference
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With