Home >Java >javaTutorial >Understanding and using java weak references

Understanding and using java weak references

(*-*)浩
(*-*)浩Original
2019-11-28 13:16:372445browse

Understanding and using java weak references

In Java, when an object is created, it is placed in the memory heap. When the GC runs, if it is found that there is no reference pointing to the object, the object will Recycled to free up memory space.

Or in other words, for an object to be recycled, two conditions must be met:

1) There is no reference pointing to it (Recommended learning: java course )

2)GC is run.

Java For simple situations, programmers do not need to manually set it blank, because in Java, for simple objects, when the method that calls it is executed, the reference pointing to it will be recycled by GC. ,

In practice, when we write code, we often set all referece pointing to a certain object to null, such as:

Person p = new Person("张三",18,"男");//强引用
...
p=null;//不再使用的时候置null

Obviously, for programmers, manually setting null objects It is cumbersome and violates the automatic recycling mechanism.

For simple situations, such as local objects generated in methods, Java does not require programmers to manually empty them. When the method calling it is executed, the reference pointing to it will be recycled by GC.

In a more complicated situation, such as using cache, because the objects in the cache are exactly what the program needs to run, as long as the program is running, the references in the cache will not be GCed, so as the references in the cache More and more objects cannot be recycled by GC and cannot be recycled automatically. At this time, developers must handle the recycling, which obviously violates the automatic recycling mechanism of Java.

In this regard, weak reference (WeakReference) was introduced in java.

When an object is only pointed to by a weak reference without any other strong reference, if the GC runs, the object will be recycled. If a strong reference exists and is associated with it, the object will not be reclaimed during garbage collection.

The syntax of WeakReference:

WeakReference<T> weakReference = new WeakReference<T>(referent);

When you want to obtain the object referenced by a weak reference, you first need to determine whether it has been recycled:

weakReference.get();

If If this method is empty, it means that the object pointed to by weakReference has been recycled.

The following is a chestnut of WeakReference:

Person class:

package com.yx.test.model;
 
/**
 * Person
 *
 * @author yx
 * @date 2019/11/26 16:28
 */
public class Person {
    private String name;
    private int age;
    private String sex;
 
    public Person() {
    }
 
    public Person(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getSex() {
        return sex;
    }
 
    public void setSex(String sex) {
        this.sex = sex;
    }
}

Test class TestWeakReference:

package com.yx.test.reference;
 
import com.yx.test.model.Person;
 
import java.lang.ref.WeakReference;
 
/**
 * TestWeakReference
 *
 * @author yx
 * @date 2019/11/26 16:30
 */
public class TestWeakReference {
    public static void main(String[] args) {
        Person p = new Person("张三",18,"男");
        WeakReference<Person> weakPerson = new WeakReference<Person>(p);
        int i=0;
        while(true){
            if(weakPerson.get()!=null){
                i++;
                System.out.println("Object is alive for "+i+" loops - "+weakPerson);
            }else{
                System.out.println("Object has been collected.");
                break;
            }
        }
    }
}

Running results:

p is alive for 1 loops - java.lang.ref.WeakReference@330bedb4
...
p is alive for 62331 loops - java.lang.ref.WeakReference@330bedb4
p is alive for 62332 loops - java.lang.ref.WeakReference@330bedb4
p has been collected.

It can be seen that after the while loop is executed tens of thousands of times, p is recycled.

Tested and ran the program many times and found that the number of loop executions during p recycling is uncertain. This is easy to understand: because this is determined by the uncertainty of GC operation.

Summary:

1. In Java, when an object is only referenced by a weak reference, if the GC runs, then the object will be recycled.

2. One of the characteristics of a weak reference is that it is uncertain when it will be recycled;

The above is the detailed content of Understanding and using java weak references. 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