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

What is the cause of Java inner class memory leak?

WBOY
Release: 2023-04-21 23:40:17
forward
1240 people have browsed it

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.");
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template