Home >Java >javaTutorial >What is the cause of Java inner class memory leak?

What is the cause of Java inner class memory leak?

WBOY
WBOYforward
2023-04-21 23:40:171242browse

Cause Analysis

1. If the anonymous inner class is not referenced, there will be a chance for recycling when the objects of the anonymous inner class are used up.

2. If the inner class is only referenced in the outer class, when the outer class is no longer referenced, the outer class and the inner class can be recycled through GC.

When the inner class reference is referenced by other classes other than the outer class, the inner class and the outer class cannot be recycled by GC. Even if the outer class is not referenced, the inner class still has a reference to the outer class).

Example

public class ClassOuter {
 
    Object object = new Object() {
        public void finalize() {
            System.out.println("inner Free the occupied memory...");
        }
    };
 
    public void finalize() {
        System.out.println("Outer Free the occupied memory...");
    }
}
 
public class TestInnerClass {
    public static void main(String[] args) {
        try {
            Test();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
    private static void Test() throws InterruptedException {
        System.out.println("Start of program.");
 
        ClassOuter outer = new ClassOuter();
        Object object = outer.object;
        outer = null;
 
        System.out.println("Execute GC");
        System.gc();
 
        Thread.sleep(3000);
        System.out.println("End of program.");
    }
}

The above is the detailed content of What is the cause of Java inner class memory leak?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete