Open full code force, code moving life, this article first public number [Craig Mowgli], pay attention to this word does not drive the old driver of the code circle

This article has been included on GitHub github.com/BeKingCodin… , my contact information and technical exchange group, welcome Star and perfect

preface

Each programming language has its own way of manipulating elements in memory. For example, in C and C++, Pointers are used.

As the leader of OOP object-oriented programming, everything is treated as an object in Java. The identifier is not the actual object, but a reference to the object.

By pointing this identifier, called a reference, to an object, you can then use the reference to manipulate the object.

Prior to JDK1.2, the definition in Java was traditional: if the value stored in a reference type of data represented the starting address of another chunk of memory, the chunk was said to represent a reference.

The garbage collection mechanism in Java relies on the concept of “reference” when deciding whether to reclaim an object. Different garbage collection algorithms have different ways to judge references, including reference counting and reachability analysis.

You can read my previous article:

Meeting with BAT, I summarized the JVM basics they would ask

“Liver after this garbage collection, not afraid to fight with the interviewer.”

Prior to JDK1.2, an object had only “referenced” and “unreferenced” states, which would not describe objects in special cases, such as a class of objects that needed to be preserved when memory was plentiful and discarded when memory was tight.

So after JDK.1.2, Java extended the concept of references into: There are four kinds of Strong Reference, Soft Reference, Weak Reference and Phantom Reference, and the strength of these four kinds of references decreases successively.

This article will take a closer look at each of these four types of citation. The code word is not easy, so don’t forget “looking” and “forwarding”.

The body of the

Strong reference

In Java, we use strong references when we declare by default, such as:

A a = new A();
Copy the code

As long as strong references are used, the garbage collector will never reclaim the referenced object. Since the memory size is fixed, the JVM simply throws outofMemoryErrors when it runs out of memory because there is no way to reclaim free space.

If you want to break the relationship between a strong reference and an object, you can explicitly assign it to NULL so that the JVM can do garbage collection at the appropriate time.

A a = null;
Copy the code

Soft references

Soft references are less powerful than strong references and represent objects that are not necessary but still useful. It takes the following form:

(1) When there is enough memory, soft reference objects will not be reclaimed.

(2) When the memory is insufficient, the system will reclaim the soft reference object.

If there is still not enough memory after the soft reference object is reclaimed, an out-of-memory exception is thrown.

Because of this nature of soft references, it is very suitable for implementing caching technologies such as web page caching, image caching, and so on.

After JDK1.2, using Java. Lang. Ref. SoftReference class soft references.

A weak reference

Weak references are even weaker, and their main feature is that when the JVM starts garbage collection, objects associated with weak references are collected regardless of whether memory is sufficient.

After JDK1.2, using Java. Lang. Ref. WeakReference weak references.

We can test this with the following small demo:

private static void testWeakReference(a) {

        for (int i = 0; i < 10; i++) {
            byte[] buff = new byte[1024 * 1024];
            WeakReference<byte[]> sr = new WeakReference<>(buff);
            list.add(sr);
        }

        System.gc(); // Proactively notify garbage collection
        for(int i=0; i < list.size(); i++){ Object obj = ((WeakReference) list.get(i)).get(); System.out.println(obj); }}Copy the code

When run, all objects associated with weak references are garbage collected.

A classic example of weak references is ThreadLocal, whose internal data structures are implemented by weak references, according to the source code.

 static class ThreadLocalMap {

        /** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. * /
        static class Entry extends WeakReference<ThreadLocal<? >>{
            /** The value associated with this ThreadLocal. */Object value; Entry(ThreadLocal<? > k, Object v) {super(k); value = v; }}}Copy the code

If you forget to remove when using ThreadLocal, you can easily leak memory. I’ll write an article about this later.

Phantom reference

A virtual reference is the weakest type of reference relationship. If an object holds only a virtual reference, it is as good as no reference at all, and it can be reclaimed at any time.

After JDK1.2, it was represented by the PhantomReference class. Looking at the source code of this class, I found that it only had a constructor and a get() method, and that its get() method simply returned null, meaning that objects could never be retrieved by virtual references. The virtual reference must be used with the ReferenceQueue ReferenceQueue.

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

    /**
     * Returns this reference object's referent.  Because the referent of a
     * phantom reference is always inaccessible, this method always returns
     * <code>null</code>.
     *
     * @return  <code>null</code>
     */

    public T get(a) {
        return null;
    }

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

conclusion

This article introduces four reference types in the Java language, which are mainly related to Java’s garbage collection mechanism and memory management. JVM as a foundation, or hope you can solid grasp.

Related articles:

Jstat: No More JVM tantrums

Full GC is responsible for frequent Online system jams

Welcome to my public account “Criag Mowgli”

See you in the next article!