Home  >  Article  >  Java  >  Strong references, soft references, weak references, and virtual references in Java development

Strong references, soft references, weak references, and virtual references in Java development

无忌哥哥
无忌哥哥Original
2018-07-23 10:05:431516browse

Due to the GC automatic recycling mechanism, Java has a relatively complete reference counting mechanism. Java divides the references held by objects into strong references, soft references, weak references, and virtual references in order of strength. Reference usage If used well, the GC can quickly recycle instances that have exceeded their life cycle, so that the machine's memory usage is at a dynamically low level. Improper use will cause memory leaks, causing the machine's memory to be exhausted and down, and we must clearly control it. The characteristics of the program you write are to keep the program in a controllable state, at least what is currently considered controllable. Let's first understand the classification of citations, and then explore the usage scenarios.

1. Strong quotation

What we usually use is strong quotation, such as:

Map<String, Object> param = new HashMap<String, Object>(16);

A quotation with the above shape is a strong quotation, as long as the quotation is still there Within the effective life cycle, the GC cannot recycle the space on the heap corresponding to the reference. Of course, the reference itself cannot be recycled. The use and rules of strong references are self-evident.

2. Soft reference

Let’s first look at how to use soft reference:

Map<String, Object> param = new HashMap<String, Object>(16);
param.put("status", 1);
SoftReference> softRef = new SoftReference>(param);
System.out.println(softRef.get().get("status"));

There is one more way to use it, but it is easy to understand. The strength of soft reference is only A kind of reference that is inferior to strong reference. Only when the virtual machine thinks that the memory is not enough, even if the reference of the soft reference is still in the life cycle, the heap space pointed by the soft reference will still be forcibly reclaimed. At this time, calling get() will return null. , so under normal circumstances, the performance of soft references is the same as that of strong references. Only when the virtual machine thinks that the memory is tight, soft references will reflect its characteristics.

3. Weak reference

How to use weak reference:

Map<String, Object> param = new HashMap<String, Object>(16);
param.put("status", 1);
WeakReference> weakRef = new WeakReference>(param);
System.out.println(weakRef.get().get("status"));

The way to use weak reference is almost the same as that of soft reference. It is a reference that is inferior to soft reference. A reference, a weak reference to an instance will not be counted by the reference counter, so if an instance does not have a strong reference, but only a weak reference, it may return null, depending on whether the GC has recycled it, as in the above example There are strong references and weak references at the same time. Let's take a look at the situation where only weak references exist:

WeakReference<Map<String, Object>> weakRef = new WeakReference<Map<String, Object>>(new HashMap<String, Object>(16));
System.gc();
System.out.println(weakRef.get());

At this time, null is printed, which means that weak references are not valid for GC's reference technology. Pay attention to this when using it. characteristic.

4. Virtual reference

The method of using virtual reference is slightly different from the above. When the GC is preparing to recycle an object, if it finds that it still has a virtual reference, it will add this virtual reference. into the reference queue associated with it. There is a passage in Section 3.2.3 of the second edition of "In-depth Understanding of the Java Virtual Machine: JVM Advanced Features and Best Practices" that says, "Virtual references are also called ghost references or phantom references. It is the weakest reference relationship. . Whether an object has a virtual reference will not affect its lifetime at all, and it is impossible to obtain an object instance through a virtual reference. The only purpose of setting a virtual reference association for an object is to be able to collect it when the object is recycled by the collector. When receiving a system notification. After JDK 1.2, the PhantomReference class is provided to implement virtual references.

Let’s first take a look at the definition of virtual reference types:

public class PhantomReference<T> extends Reference<T> {

    public T get() {
        return null;
    }

    public PhantomReference(T referent, ReferenceQueue<? super T> q) {
        super(referent, q);
    }

}

We see that he only A constructor, and a reference queue must be specified. The following code shows a Demo:

ReferenceQueue<Map<String, Object>> q = new ReferenceQueue<Map<String, Object>>();
PhantomReference<Map<String, Object>> phantomRef = new PhantomReference<Map<String, Object>>(new HashMap<String, Object>(16), q);
System.gc();
Thread.sleep(1000);
System.out.println(phantomRef.get());
System.out.println(q.poll());

The printed result is null and an instance of PhantomReference, which verifies that an object instance cannot be obtained through a virtual reference and the reference is Facts added to the reference queue.

The above is the detailed content of Strong references, soft references, weak references, and virtual references in Java development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn