0

Will passing outer object class object to static inner creates a memory leak?

And how I can check whether it will create the memory leak?

Below is what I am looking for where I have created the inner and outer class, and the way I am planning to use and pass the object.

My main doubt is because I think at some point even though OuterClass object would no more be referenced from anywhere still it would not be GC'ed because InnerClass (which is a STATIC class) is holding a reference of the it. So, I feel this would cause a memory leak.

public class OuterClass {

    private int id;
    private String name;

    public static class InnerClass{
        OuterClass outerClass;

        public InnerClass(OuterClass outerClass) {
            this.outerClass = outerClass;
        }

        public void printOuterClassDetails(){
            System.out.println(outerClass.getId() + " | " + outerClass.getName());
        }
    }

    public OuterClass(int i, String string) {
        this.id = i;
        this.name = string;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        OuterClass outerClass = new OuterClass(1, "A");
        OuterClass.InnerClass innerClass = new InnerClass(outerClass);
        innerClass.printOuterClassDetails();
    }

}
pjj
  • 2,015
  • 1
  • 17
  • 42
  • This is no different at all from passing any reference into the constructor of a class. The fact it is a nested class is irrelevant. – Andy Turner Jan 02 '19 at 11:56
  • https://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java – Ricola Jan 02 '19 at 11:57
  • BTW: "static inner" is a contradiction: inner classes are [by definition](https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.1.3) not static. This is a *nested* class. – Andy Turner Jan 02 '19 at 11:57
  • @AndyTurner But isn't this true that even though outer class object would not be referenced from anywhere else but still it would not be GC'ed because inner class (which is static) is holding a reference of it? – pjj Jan 02 '19 at 13:10
  • @pjj the inner class doesn't hold a reference to anything. The instance of that class, an object, holds a reference to an instance of the outer class. Not because it is an inner class, but because you passed a reference to the instance of the outer class. You are mixing two concepts: classes and objects. – NickL Jan 02 '19 at 15:53

0 Answers0