'java WeakReference. GC rarely occurs when the Old Generation area is full. (picture)

The test was conducted using the WeakReference class. Look at the code.

public class ReferenceClassTest {
    private static List<WeakReference<BigData>> weakReferences = new LinkedList<>();
    private static List<SoftReference<BigData>> softReferences = new LinkedList<>();

    static class BigData {
        private int[] array = new int[2500];
    }

    public static void weakReferenceTest() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            while (true) {
                weakReferences.add(new WeakReference<>(new BigData()));
            }
        } catch (OutOfMemoryError e) {
            System.out.println("out of memory");
        }
    }

    public static void softReferenceTest() {

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            while (true) {
                softReferences.add(new SoftReference<>(new BigData()));
            }
        } catch (OutOfMemoryError e) {
            System.out.println("out of memory");
        }
    }
}

And the picture is the GC result measured using the visualGC program.

weakReferenceTest

weakReferenceTest

When you run "weakReferenceTest", heap memory usage continues to increase. Old Generation memory usage does not decrease when garbage collection occurs (Eventually, the Old Generation area fills up ). GC does not appear to occur even though the object is encapsulated with the WeakReference class.

softReferenceTest

softReferenceTest

This result looks very different from the result of running "softReferenceTest".

Why did this result happen?



Solution 1:[1]

While the BigData objects may not be strongly reachable, the WeakReference and SoftReference objects that point to them are reachable. The weakReferences and softReferences collections are likely the source of the memory usage.

You can confirm by taking a heap dump (using tools like jmap) and viewing the heap usage using tools like MAT.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carl Mastrangelo