References to objects in the Java language are divided into four levels, namely strong, soft, weak, and virtual.
This article is only for weak references in Java for some analysis, such as discrepancies, please also correct.
Before parsing a weak reference, first describe a concept: what is an object reachable and the object unreachable state.
Actually very simple, I give an example:
There are now two classes Class A, and two instances of their classes are generated on the JVM, instance A instance B, respectively.
There are the following expressions:
A = new A ();
b b = new B ();
Two strongly referenced objects are generated, OK, so this time I'll make a change:
A = new A ();
b b = new B (a);
B's default constructor is to require an instance of a as a parameter, then A and B will produce a dependency, it can be said that A and B have a dependency, We then use a diagram near the memory structure to express:
A is a reference to object A, B is a reference to object B, and object B also depends on object A, so at this point we think that from object B we can reach object A.
So I changed the code a bit.
A = new A ();
b b = new B (a);
A = null;
A object's reference A is empty, a no longer points to the address of object A, we all know that when an object is no longer referenced by other objects, it will be recycled by GC, it is obviously timely a=null, then a object can not be recycled, because B is still dependent on a, at this time, causing a memory leak!
So how do you avoid memory leaks in the above example?
Very simple:
A = new A ();
b b = new B (a);
A = null;
b = null;
At this point the B object is no longer referenced, the A object is only referenced by the B object, although the GC can also reclaim both of them because they are in an unreachable area.
The weak references are coming!
A = new A ();
WeakReference wr = new WeakReference (a);
b b = new B (a);
When A=null, this time A is only weak reference dependency, then the GC will immediately reclaim a object, which is the advantage of weak references! He can help you to properly dispose of objects and cause unnecessary memory leaks when you are not very clear about object structure and topology!!
Talk about the WeakReference in Java