Article From:

1.In a blog today, ThreadLocal uses a weak reference to find that it does not really understand the difference between weak and strong references, so I wrote the following code based on the current understanding of strong and weak references. I hope that friends of the community can help me to answer it.
2.The code is as follows:
Class A:

    import java.lang.ref.WeakReference;
    public class A<T> extends WeakReference<T> {
        public A(T referent) {

Class B:

    public class B {

Class C:

    import java.lang.ref.WeakReference;
    public class C {
        private B b = new B();
        private WeakReference<B> a = new A<B>(b);

        public WeakReference<B> getA() {
            return a;

3.What is the reference relationship between class A and class B, class A and class C, class B and class C in the above code?

If I adjust the code of the class A as follows:Import java.lang.ref.WeakReference;Private B B;Public class A< T> eXtends WeakReference< T> {Public A (T referent) {Super (referent);}}

What is the reference relationship and the change?

Answer 0:

The execution of GC is clear.

Answer 1:

1.First this wayClass A and class B, class A and class C, class B and class CWhat is the reference relationship?
To rectify it, it should be said that citation is a strong reference or weak reference to an example.
For instance

Object a=new Object()

Above I created an Object object using new, a – & gt; new object () in the object created with new Object (), which is a strong reference pattern

2.Weak reference: it will be recycled when GC is garbage collected.

Object a=new Object()
WeakReference<Object> wf = new WeakReference<Object>(obj);
Object b=wf.get()

The B obtained here is a weak reference, and because of the use of WeakReference to create the B object obtained by get (), of course, the object may be a null object recovered by the garbage collection mechanism, at that time, B is a weak reference to Objectd and a is OStrong reference to bject
When I add a word to the back:a=null;The object itself created by the new Object () is released due to strong references, resulting in only weak references.

In other words:

1.As you can see in the diagram, new Objet () is a strongly referenced object when the a = null statement is not executed and cannot be recycled by the garbage collection mechanism!2. when a=null is executed, the strong reference relation ends, with only weak reference relation. The object is weak reference.Object

Similar Posts:

Link of this Article: Strong and weak references

Leave a Reply

Your email address will not be published. Required fields are marked *