This is the 29th day of my participation in Gwen Challenge

preface

In learning the Java language, we know that the Java language is strongly typed, which defines specific data types for each type of data and allocates different sizes of memory space in memory. There are eight basic data types that store values (int, char, float, etc.) and three reference types (class, interface, and array). Reference types store addresses.

All primitive type assignments are passed by value, whereas reference types are passed by reference. Today, we’ll talk about object references in Java.

Objects and references

Unlike c++, where a pointer points to a block of memory, Java uses a reference to manipulate the address of an object. We usually store this type of reference in a certain memory space (stack space), and then use the heap space to store the referenced object, as shown in the following figure:

A and B are different references to different objects “hello” and “Hello world”.

We can also change the object to which a reference points, and an object can support multiple references.

Two, four kinds of quotes

Why are there four reference types in Java? We know that the JVM GC mechanism it has reference counting method, if an object is cited, is not recycled, before JDK1.2, an object only “has been quoted” and “not cited” two states, at the time of memory use, if we can recycle some referenced memory, can achieve the performance requirements of ascension.

Java defines a class for Reference types called Reference. After JDK1.2, object references are divided into four states: strong, soft, weak, and virtual. In this way, you can control the life cycle of the object more flexibly. Its inheritance relationship is shown as follows:

This is a very good metaphor to sum up the relationship between these four references.

1, strong quotes are like the first wife, the relationship is very stable.

2, soft quotes like the second wife, may fall out of favor at any time, but there is also the possibility of righting.

Weak quotation is like a lover, the relationship is not stable, may run away with others.

A false reference is a dream lover, only in the dream.

— Message from sea Monster brother from Java Core Technology lecture 36

2.1 Strong Reference

In Java, a strong reference is an object that can be found directly through a GC root object and will not be reclaimed, whether or not there is enough memory.

Strong references are common in program code, and even if memory runs out, the JVM would rather throw an OutOfMemory error than reclaim an object, as in the following:

String a="hello world";
Object o =new Object();
Copy the code

However, if you go beyond the scope of a local variable, or assign a strong reference to NULL, or call the clear () method, object collection can be done.

2.2 Soft Reference Soft Reference

Soft references mean that referenced objects are reclaimed only if memory runs out.

Note that memory is not collected when there is insufficient memory. Soft references are often used to implement memory-sensitive caching, such as loading an image if there is extra memory when loading an article, and not loading the image cache if memory is tight.

public class test { public static void main(String[] args) { SoftReference<String> str = new SoftReference<String>("hello world"); System.out.println(str.get()); System.gc(); System.out.println(str.get()); }}Copy the code

2.3 Weak Reference Weak Reference

Weak references have a lower level. When garbage collection is enabled, weakly referenced objects will be collected regardless of whether memory is dead or not

public class test { public static void main(String[] args) { WeakReference<String> str = new WeakReference<>(new String("hello world")); System.out.println(str.get()); System.gc(); System.out.println(str.get()); }}Copy the code

Output result:

hello world
null
Copy the code

2.4 Phantom Reference

A virtual reference is the weakest type of reference, it can be reclaimed at any time, and we cannot access the reference object through it,

Often, the sole purpose of setting a virtual reference to an object is to track the garbage collection process, for example, if the object receives a notification from the system when it is collected.

Looking at the source code for this class, you see that it has only one constructor and one get() method, and that its get() method simply returns null.

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

   
    public T get() {
        return null;
    }

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

Copy the code

The virtual reference must also be used in conjunction with the ReferenceQueue (ReferenceQueue). When the GC begins to reclaim an object, it determines that there are only virtual references to the object and adds the virtual reference to the associated ReferenceQueue before the object is reclaimed. Therefore, we can look in the reference queue to see if a reference is in the queue, and then conclude that the object has been garbage collected, issuing a system notification.

Conclusion:

Reference types Recovery time use
Strong reference This object can be set to NULL and so on Widely used in projects
Soft references It is collected only when there is insufficient memory during GC Used in memory sensitive caches
A weak reference When the GC recycling Object cache usage
Phantom reference When the GC recycling Used with reference queues, garbage collection sends notifications

References:

  • Java Core Technology lecture 36