1
00:00:01,500 --> 00:00:09,155
How do these reference types work? We'll use an example here of a weak reference, but similar ideas apply to

2
00:00:09,155 --> 00:00:14,155
soft references assuming that the softly referenced object is being garbage collected.

3
00:00:14,155 --> 00:00:19,155
The idea is something like this. We allocate the new object, so here we're doing Person person = new Person,

4
00:00:19,155 --> 00:00:25,155
and we have a strong reference to this person object and then we come along and we create a weak reference to

5
00:00:25,155 --> 00:00:32,155
the object and the way we do that is by doing new WeakReference and passing the weak reference a reference

6
00:00:32,155 --> 00:00:39,155
to our person object, so the weak reference is now wrapped up, the person's strong reference, and we show

7
00:00:39,155 --> 00:00:44,155
that here as we have a person object with a reference to it, we have a weak reference object with a strong

8
00:00:44,155 --> 00:00:51,155
reference to that, and the WeakReferenceObject holds a weak reference onto the person object shown here by

9
00:00:51,155 --> 00:00:59,155
the dotted line. If we then take our weak reference and call a get on it that returns a strong reference to

10
00:00:59,155 --> 00:01:05,155
the object, so we say person p equals Worker Roles.get, and that returns a strong reference to the person

11
00:01:05,155 --> 00:01:11,155
object that already exists. Now suppose we set the person reference to null.

12
00:01:11,155 --> 00:01:18,155
Now, at this point, we're assuming that no garbage collection happens, so we have no strong reference to the

13
00:01:18,155 --> 00:01:25,155
person object now, but we still have a weak reference to it, and so long as there's no Garbage Collector that

14
00:01:25,155 --> 00:01:33,155
object is still alive. We can now call wr.get and return the strong reference to that object, so so long as

15
00:01:33,155 --> 00:01:39,155
no garbage collection has happened, that object is still available, and can be retrieved through the weak

16
00:01:39,155 --> 00:01:40,155
reference.

17
00:01:40,155 --> 00:01:45,155
However, if you have a scenario that was similar to the above, but we set the person reference to null, we

18
00:01:45,155 --> 00:01:49,155
set the strong reference to null, and then the Garbage Collector runs, and we show that here by calling

19
00:01:49,155 --> 00:01:57,155
System.gc. Now the person object goes away, so a person reference is set to null and the weakly referenced

20
00:01:57,155 --> 00:02:02,155
object is now no longer referencing anything. At this point,

21
00:02:02,155 --> 00:02:08,155
if we called wr.get, then we return null, so p is now referencing null, person's representing null, there's

22
00:02:08,155 --> 00:02:12,155
no strongly referenced object in memory for us to reference any more,

23
00:02:12,155 --> 00:02:17,000
so let's write some code to see that.


