Strong weak dangling reference only experience too, to remember

Strong weak phantom reference before learning time, just skim to see blog, and do not write their own code to practice, to prove, leading after each reading, and before long forgot, later determined to have to knock yourself knock Code, so as to make more impressive, an old saying: paper come Zhongjue know this practice is essential.

Four references in Java

There are four Java reference types: strong references, soft references, weak references, phantom references.

Why these four Java design reference

Java memory allocation and garbage collection, programmers do not need to be responsible, to take charge of all the great JVM, whether an object can be recycled, mainly to see if there are references to this object, say a professional point called reachability analysis .

The main purpose of the four Java design reference is twofold:

  1. It allows the programmer to determine the life cycle of an object through code;
  2. There use garbage collection.

Strong references

A strong reference is the most common form of reference, we write the code, 99.9999% are strong references:

Object o = new Object();
复制代码

This is a strong reference, is not everywhere in the code, the most cordial. As long as there is a strong reference to an object associated with it, the object will never be recovered, even if out of memory, JVM would rather throw OOM, will not go to recycling.

So when can it be recycled? When the strong association between the reference and the object is interrupted, it can be recovered.

We can manually correlate to the interrupt, the method is particularly simple:

        o = null;
复制代码

We can call the GC manual to see if the strong correlation between the reference and the object is interrupted, the resource will not be recovered, for easier, more clearly observed in the case of recovery, we need to write a new class, and try write finalize method, let's carry out this experiment:

public class Student {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Student 被回收了");
    }
}
复制代码
public static void main(String[] args) {
        Student student = new Student();
        student = null;
        System.gc();
}
复制代码

operation result:

Student 被回收了
复制代码

We can clearly see that the resources are recovered.

Of course, in the actual development, do not override the finalize method

In the actual development, we see some objects are manually assigned to NULL, it is very likely that in order to "specially reminded" JVM garbage this resource can be recovered.

Soft references

Here take a look at how to create a soft reference:

 SoftReference<Student>studentSoftReference=new SoftReference<Student>(new Student());
复制代码

Soft reference is to an object wrapped with SoftReference moment, when we need to refer to objects from the object gets wrapped soft, as long as what you can get:

        SoftReference<Student>studentSoftReference=new SoftReference<Student>(new Student());
        Student student = studentSoftReference.get();
        System.out.println(student);
复制代码

Soft references What are the characteristics of it: when there is insufficient memory, will trigger the JVM GC, if the GC, or lack of memory, will be wrapped soft object references to kill, that is, only in the lack of memory, JVM will recover the object .

Still the same, the experiment must be done in order to impress:

        SoftReference<byte[]> softReference = new SoftReference<byte[]>(new byte[1024*1024*10]);
        System.out.println(softReference.get());
        System.gc();
        System.out.println(softReference.get());

        byte[] bytes = new byte[1024 * 1024 * 10];
        System.out.println(softReference.get());
复制代码

I define a soft reference object, which wrapped a byte [], byte [] takes up 10M, and then create a 10Mbyte [].

Run the program, you need to take one parameter:

-Xmx20M
复制代码

It represents the maximum heap memory is 20M.

operation result:

[B@11d7fff
[B@11d7fff
null
复制代码

After you can clearly see done manually GC, soft reference object wrapped byte [] still alive and well, but when we have created a 10M byte [], the maximum heap memory is not enough, so the soft reference object wrapped the byte [] to get rid of, if not kill, throws OOM.

Soft references in the end what use is it? More suitable for use as a cache, when there is enough memory, you can get a normal cache when the memory is not enough, you will first get rid of the cache, and will not immediately throw OOM.

Weak references

Use soft and weak references cited similar, but the keyword into a WeakReference:

        WeakReference<byte[]> weakReference = new WeakReference<byte[]>(new byte[1024*1024*10]);
        System.out.println(weakReference.get());
复制代码

There are no weak references characteristic of memory is sufficient, as long as the GC happens, it will be recycled:

        WeakReference<byte[]> weakReference = new WeakReference<byte[]>(new byte[1]);
        System.out.println(weakReference.get());
        System.gc();
        System.out.println(weakReference.get());
复制代码

operation result:

[B@11d7fff
null
复制代码

We can clearly see clearly still plenty of memory, but triggered GC, resources or be recycled. Weak references are used in many places, such as ThreadLocal, WeakHashMap.

False quote

Also known as virtual reference phantom reference, we take a look at its use:

        ReferenceQueue queue = new ReferenceQueue();
        PhantomReference<byte[]> reference = new PhantomReference<byte[]>(new byte[1], queue);
        System.out.println(reference.get());
复制代码

And the use of virtual reference cited above said the soft, weak references difference is still getting bigger, let's ReferenceQueue no matter what the hell is directly run:

null
复制代码

Even print out the null, we get to look at the source method:

    public T get() {
        return null;
    }
复制代码

This is several meanings, even directly returned null.

This is one of the characteristics of the virtual reference: Unable to get to a real object referenced by the phantom reference.

What is the meaning of existence that phantom reference is it? This was back at the top of our code, we copy the code down, lest they turned up again:

        ReferenceQueue queue = new ReferenceQueue();
        PhantomReference<byte[]> reference = new PhantomReference<byte[]>(new byte[1], queue);
        System.out.println(reference.get());
复制代码

Create a virtual reference object, apart from the parcel object passed into it, also passed a ReferenceQueue, from the name you can see that it is a queue.

The second feature phantom reference is phantom reference must be used with ReferenceQueue, when GC ready to reclaim an object, if it is found that there is a virtual reference will be prior to recovery, this added to the virtual reference ReferenceQueue associated in.

We used to practice it under the code:

        ReferenceQueue queue = new ReferenceQueue();
        List<byte[]> bytes = new ArrayList<>();
        PhantomReference<Student> reference = new PhantomReference<Student>(new Student(),queue);
        new Thread(() -> {
            for (int i = 0; i < 100;i++ ) {
                bytes.add(new byte[1024 * 1024]);
            }
        }).start();

        new Thread(() -> {
            while (true) {
                Reference poll = queue.poll();
                if (poll != null) {
                    System.out.println("虚引用被回收了:" + poll);
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        scanner.hasNext();
    }
复制代码

operation result:

Student 被回收了
虚引用被回收了:java.lang.ref.PhantomReference@1ade6f1
复制代码

Our simple analysis under the code: the first thread to the collection of stuffed data, as more and more data, GC will certainly happen. The second thread loop, data from the queue to get inside, if out of the data is not null, then print it out.

It can be seen from the results: When the GC occurred, the virtual reference will be recovered and recycled into the notification will in ReferenceQueue.

False quote what use is it? In NIO, the references on the use of the virtual memory management heap outside.

These are all of the contents of this blog.

Guess you like

Origin juejin.im/post/5e65b8096fb9a07cbb6e4a43