How do these reference types work? We'll use an example here of a weak reference, but similar ideas apply to
soft references assuming that the softly referenced object is being garbage collected.
The idea is something like this. We allocate the new object, so here we're doing Person person = new Person,
and we have a strong reference to this person object and then we come along and we create a weak reference to
the object and the way we do that is by doing new WeakReference and passing the weak reference a reference
to our person object, so the weak reference is now wrapped up, the person's strong reference, and we show
that here as we have a person object with a reference to it, we have a weak reference object with a strong
reference to that, and the WeakReferenceObject holds a weak reference onto the person object shown here by
the dotted line. If we then take our weak reference and call a get on it that returns a strong reference to
the object, so we say person p equals Worker Roles.get, and that returns a strong reference to the person
object that already exists. Now suppose we set the person reference to null.
Now, at this point, we're assuming that no garbage collection happens, so we have no strong reference to the
person object now, but we still have a weak reference to it, and so long as there's no Garbage Collector that
object is still alive. We can now call wr.get and return the strong reference to that object, so so long as
no garbage collection has happened, that object is still available, and can be retrieved through the weak
reference.
However, if you have a scenario that was similar to the above, but we set the person reference to null, we
set the strong reference to null, and then the Garbage Collector runs, and we show that here by calling
System.gc. Now the person object goes away, so a person reference is set to null and the weakly referenced
object is now no longer referencing anything. At this point,
if we called wr.get, then we return null, so p is now referencing null, person's representing null, there's
no strongly referenced object in memory for us to reference any more,
so let's write some code to see that.